package dashboard

import (
	"errors"
	"fmt"
	"gitcode.com/G-YT/iHealth25/server/global"
	"gitcode.com/G-YT/iHealth25/server/model/assess"
	"gitcode.com/G-YT/iHealth25/server/model/body"
	"gitcode.com/G-YT/iHealth25/server/model/catering"
	"gitcode.com/G-YT/iHealth25/server/model/dashboard"
	"gitcode.com/G-YT/iHealth25/server/model/disease"
	"gitcode.com/G-YT/iHealth25/server/model/health"
	"gitcode.com/G-YT/iHealth25/server/model/hierarchy"
	"gitcode.com/G-YT/iHealth25/server/model/manager"
	"gitcode.com/G-YT/iHealth25/server/model/system"
	"gitcode.com/G-YT/iHealth25/server/model/user"
	userReq "gitcode.com/G-YT/iHealth25/server/model/user/request"
	userRes "gitcode.com/G-YT/iHealth25/server/model/user/response"
	"gorm.io/gorm"
	"sort"
	"strconv"
	"strings"
	"time"
)

type BordService struct {
}

func (s *BordService) GetAllUserData(ScID uint) (userDashboard dashboard.User, err error) {
	today := time.Now().Format("2006-01-02")
	yesterday := time.Now().AddDate(0, 0, -1)
	var register int64
	err = global.GVA_DB.Model(&user.User{}).Count(&register).Error
	if err != nil {
		return
	}
	userDashboard.Register = register
	var vip int64
	err = global.GVA_DB.Model(&user.User{}).Where("types = 2").Count(&vip).Error
	if err != nil {
		return
	}
	userDashboard.VIP = vip
	var vipExpire int64
	err = global.GVA_DB.Model(&user.User{}).Where("types = 3").Count(&vipExpire).Error
	userDashboard.Expire = vipExpire
	// 性别
	var man int64
	var woman int64
	ageGroup := make(map[string]int64)

	var users []user.User
	err = global.GVA_DB.Find(&users, "birthday is not null").Error
	if err != nil {
		return
	}
	// 年龄占比:25以下
	//         26-35
	//         36-45
	//         46-55
	//         56-65
	//         66-75
	//         76-85
	//         85以上
	for i := range users {
		if users[i].Sex == 1 {
			man++
		}
		if users[i].Sex == 2 {
			woman++
		}
		//当前时间 - users[i].Birthday 计算年龄
		age := time.Now().Year() - users[i].Birthday.Year()
		if age < 25 {
			ageGroup["25以下"]++
		} else if age >= 25 && age <= 35 {
			ageGroup["26-35"]++
		} else if age >= 36 && age <= 45 {
			ageGroup["36-45"]++
		} else if age >= 46 && age <= 55 {
			ageGroup["46-55"]++
		} else if age >= 56 && age <= 65 {
			ageGroup["56-65"]++
		} else if age >= 66 && age <= 75 {
			ageGroup["66-75"]++
		} else if age >= 76 && age <= 85 {
			ageGroup["76-85"]++
		} else if age > 85 {
			ageGroup["85以上"]++
		}
	}
	userDashboard.AgePie = []dashboard.Pie{
		{
			Name:  "25以下",
			Value: ageGroup["25以下"],
		},
		{
			Name:  "26-35",
			Value: ageGroup["26-35"],
		},
		{
			Name:  "36-45",
			Value: ageGroup["36-45"],
		},
		{
			Name:  "46-55",
			Value: ageGroup["46-55"],
		},
		{
			Name:  "56-65",
			Value: ageGroup["56-65"],
		},
		{
			Name:  "66-75",
			Value: ageGroup["66-75"],
		},
		{
			Name:  "76-85",
			Value: ageGroup["76-85"],
		},
		{
			Name:  "85以上",
			Value: ageGroup["85以上"],
		},
	}

	userDashboard.SexPie = []dashboard.Pie{
		{
			Name:  "男",
			Value: man,
		},
		{
			Name:  "女",
			Value: woman,
		},
	}

	var registerUsers []user.User
	err = global.GVA_DB.Where("created_at > ?", time.Now().AddDate(0, 0, -15)).Preload("HealthManager").Find(&registerUsers).Error
	if err != nil {
		return
	}
	var addLine = make(map[string][]user.User)
	// 自动填充key为最近七天的格式化
	t := time.Now()
	for i := 0; i < 15; i++ {
		date := t.AddDate(0, 0, -i).Format("2006-01-02")
		addLine[date] = make([]user.User, 0)
	}

	for i := range registerUsers {
		addLine[registerUsers[i].CreatedAt.Format("2006-01-02")] = append(addLine[registerUsers[i].CreatedAt.Format("2006-01-02")], registerUsers[i])
	}

	userDashboard.AddLine = addLine
	var foodPlan []catering.Food

	//err = global.GVA_DB.Find(&foodPlan, "date >= ? and date <= ?", today, tomorrow).Error
	err = global.GVA_DB.
		Joins("left join fd_user on fd_food.user_id = fd_user.id").
		Find(&foodPlan, "date >= ? and date <= ?", yesterday, today).Error
	if err != nil {
		return
	}
	var planHistogram = make(map[string]int64)
	planHistogram["已完成"] = 0
	planHistogram["未完成"] = 0
	type kv struct {
		Key   uint
		Value int
	}
	var ss []kv
	for _, food := range foodPlan {
		schedule := getSchedule(food)
		ss = append(ss, kv{food.UserID, schedule})
		if schedule == 100 {
			planHistogram["已完成"]++
			continue
		}
		planHistogram["未完成"]++
	}
	userDashboard.PlanHistogram = planHistogram
	sort.Slice(ss, func(i, j int) bool {
		return ss[i].Value > ss[j].Value
	})
	sstop10 := ss
	if len(ss) > 10 {
		sstop10 = ss[:10]
	}
	for i := range sstop10 {
		var u user.User
		err = global.GVA_DB.First(&u, sstop10[i].Key).Error
		if err != nil {
			return
		}
		userDashboard.PlanRank = append(userDashboard.PlanRank, dashboard.RankInfo{
			Username: u.Name,
			Count:    sstop10[i].Value,
		})
	}
	var diseaseReportRecord []disease.DiseaseReportRecord
	// 按照created_at倒序排列  按照 uid 进行group 取 bzid
	err = global.GVA_DB.
		Joins("left join fd_user on fd_disease_report_record.uid = fd_user.id").
		Select("fd_disease_report_record.created_at as created_at, fd_disease_report_record.uid as uid, fd_disease_report_record.bz_ids as bz_ids").
		Group("uid").
		Order("created_at desc").
		Find(&diseaseReportRecord).Error
	if err != nil {
		return
	}
	var bzids []string
	var bzidMap = make(map[string]*dashboard.DiseaseRankInfo)
	for i := range diseaseReportRecord {
		bzArr := strings.Split(diseaseReportRecord[i].BzIDs, ",")
		for i2 := range bzArr {
			if _, ok := bzidMap[bzArr[i2]]; ok {
				bzidMap[bzArr[i2]].Count++
				bzidMap[bzArr[i2]].UserIDs = append(bzidMap[bzArr[i2]].UserIDs, diseaseReportRecord[i].Uid)
				continue
			}
			bzidMap[bzArr[i2]] = &dashboard.DiseaseRankInfo{
				Username: "",
				Count:    1,
				UserIDs:  make([]uint, 0),
			}
			bzidMap[bzArr[i2]].UserIDs = append(bzidMap[bzArr[i2]].UserIDs, diseaseReportRecord[i].Uid)
		}
		bzids = append(bzids, bzArr...)
	}
	var diseaseList []disease.Disease
	err = global.GVA_DB.Find(&diseaseList, "id in (?)", bzids).Error
	for i := range diseaseList {
		sid := strconv.Itoa(int(diseaseList[i].ID))
		if _, ok := bzidMap[sid]; ok {
			bzidMap[sid].Username = diseaseList[i].Name
		}
	}
	for _, v := range bzidMap {
		userDashboard.DiseaseRank = append(userDashboard.DiseaseRank, *v)
	}

	var fdVideoArticle []hierarchy.FdArticle
	var fdGraphicArticle []hierarchy.FdArticle
	var fdAudioArticle []hierarchy.FdArticle
	var fdArticle []hierarchy.FdArticle
	var levelCount = make(map[int]int64)
	var HierarchyPie []dashboard.Pie
	err = global.GVA_DB.Model(&hierarchy.FdArticleVideo{}).Find(&fdVideoArticle).Error
	err = global.GVA_DB.Model(&hierarchy.FdArticleGraphic{}).Find(&fdGraphicArticle).Error
	err = global.GVA_DB.Model(&hierarchy.FdArticleAudio{}).Find(&fdAudioArticle).Error
	fdArticle = append(fdArticle, fdVideoArticle...)
	fdArticle = append(fdArticle, fdGraphicArticle...)
	fdArticle = append(fdArticle, fdAudioArticle...)
	for i := range fdArticle {
		if fdArticle[i].LevelOneID != nil {
			levelCount[*fdArticle[i].LevelOneID]++
		}
	}
	var levelOne []hierarchy.LevelOne
	err = global.GVA_DB.Find(&levelOne).Error
	for i := range levelOne {
		HierarchyPie = append(HierarchyPie, dashboard.Pie{
			Name:  levelOne[i].Value,
			Value: levelCount[int(levelOne[i].ID)],
		})
	}
	userDashboard.HierarchyPie = HierarchyPie

	// 统计在管人数
	var memberCount int64
	err = global.GVA_DB.Model(&user.User{}).Where("types = 2").Count(&memberCount).Error
	startTime := yesterday.Format("2006-01-02")
	endTime := time.Now().Format("2006-01-02")
	// 统计服务人数
	var serviceCount int64
	err = global.GVA_DB.Model(&manager.MessageRemind{}).
		Joins("left join fd_health_manager on fd_message_remind.hm_id = fd_health_manager.hm_id").
		Where("fd_message_remind.created_at BETWEEN ? AND ?", startTime, endTime).Count(&serviceCount).Error
	userDashboard.ServiceHistogram = map[string]int64{
		"manage_num":       memberCount,
		"service_num":      serviceCount,
		"no_service_count": memberCount - serviceCount, // 直接减法更快
	}

	// 统计方案完成进度数量(总)
	var percents []catering.Food
	err = global.GVA_DB.Find(&percents).Error
	var num100 uint
	var num80 uint
	var num60 uint
	var num40 uint
	var num20 uint
	var num0 uint
	for i := range percents {
		if percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Brain != nil && percents[i].Sport != nil {
			num100++
		} else if (percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Brain != nil) ||
			(percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Sport != nil) ||
			(percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Brain != nil && percents[i].Sport != nil) ||
			(percents[i].Breakfast != nil && percents[i].Dinner != nil && percents[i].Brain != nil && percents[i].Sport != nil) ||
			(percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Brain != nil && percents[i].Sport != nil) {
			num80++
		} else if (percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Dinner != nil) ||
			(percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Brain != nil) ||
			(percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Sport != nil) ||
			(percents[i].Breakfast != nil && percents[i].Dinner != nil && percents[i].Brain != nil) ||
			(percents[i].Breakfast != nil && percents[i].Dinner != nil && percents[i].Sport != nil) ||
			(percents[i].Breakfast != nil && percents[i].Brain != nil && percents[i].Sport != nil) ||
			(percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Brain != nil) ||
			(percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Sport != nil) ||
			(percents[i].Lunch != nil && percents[i].Brain != nil && percents[i].Sport != nil) ||
			(percents[i].Dinner != nil && percents[i].Brain != nil && percents[i].Sport != nil) {
			num60++
		} else if (percents[i].Breakfast != nil && percents[i].Lunch != nil) ||
			(percents[i].Breakfast != nil && percents[i].Dinner != nil) ||
			(percents[i].Breakfast != nil && percents[i].Brain != nil) ||
			(percents[i].Breakfast != nil && percents[i].Sport != nil) ||
			(percents[i].Lunch != nil && percents[i].Dinner != nil) ||
			(percents[i].Lunch != nil && percents[i].Brain != nil) ||
			(percents[i].Lunch != nil && percents[i].Sport != nil) ||
			(percents[i].Dinner != nil && percents[i].Brain != nil) ||
			(percents[i].Dinner != nil && percents[i].Sport != nil) ||
			(percents[i].Brain != nil && percents[i].Sport != nil) {
			num40++
		} else if (percents[i].Breakfast != nil) || (percents[i].Lunch != nil) || (percents[i].Dinner != nil) || (percents[i].Brain != nil) || (percents[i].Sport != nil) {
			num20++
		} else {
			num0++
		}
	}
	userDashboard.PlanPercent = map[string]uint{
		"num100": num100,
		"num80":  num80,
		"num60":  num60,
		"num40":  num40,
		"num20":  num20,
		"num0":   num0,
	}
	//userDashboard = dashboard.User{
	//	Register: 2389427,
	//	VIP:      1433656,
	//	Expire:   955771,
	//	AgePie: []dashboard.Pie{
	//		{
	//			Name:  "25以下",
	//			Value: 47789,
	//		},
	//		{
	//			Name:  "26-35",
	//			Value: 119471,
	//		},
	//		{
	//			Name:  "36-45",
	//			Value: 358414,
	//		},
	//		{
	//			Name:  "46-55",
	//			Value: 477885,
	//		},
	//		{
	//			Name:  "56-65",
	//			Value: 597357,
	//		},
	//		{
	//			Name:  "66-75",
	//			Value: 477885,
	//		},
	//		{
	//			Name:  "76-85",
	//			Value: 238943,
	//		},
	//		{
	//			Name:  "85以上",
	//			Value: 71683,
	//		},
	//	},
	//	SexPie: []dashboard.Pie{
	//		{
	//			Name:  "男",
	//			Value: 716828,
	//		},
	//		{
	//			Name:  "女",
	//			Value: 1672599,
	//		},
	//	},
	//	RegistrantsRank: []dashboard.RankInfo{},
	//	AddLine: map[string][]user.User{
	//		"2023-05-01": []user.User{
	//			{
	//				Name: "fdNick_0511",
	//			},
	//		},
	//		"2025-06-15": []user.User{
	//			{
	//				Name: "fdNick_4132",
	//			},
	//		},
	//		"2025-06-16": []user.User{
	//			{
	//				Name: "fdNick_0541",
	//			},
	//		},
	//		"2025-06-17": []user.User{
	//			{
	//				Name: "fdNick_6213",
	//			},
	//		},
	//		"2025-06-18": []user.User{
	//			{
	//				Name: "fdNick_8383",
	//			},
	//			{
	//				Name: "fdNick_1006",
	//			},
	//		},
	//		"2025-06-19": []user.User{
	//			{
	//				Name: "fdNick_0114",
	//			},
	//		},
	//		"2025-06-20": []user.User{
	//			{
	//				Name: "fdNick_0841",
	//			},
	//		},
	//		"2025-06-21": []user.User{
	//			{
	//				Name: "fdNick_0241",
	//			},
	//		},
	//		"2025-06-22": []user.User{
	//			{
	//				Name: "fdNick_6341",
	//			},
	//		},
	//		"2025-06-23": []user.User{
	//			{
	//				Name: "fdNick_7421",
	//			},
	//			{
	//				Name: "fdNick_9043",
	//			},
	//			{
	//				Name: "fdNick_3654",
	//			},
	//			{
	//				Name: "fdNick_1316",
	//			},
	//		},
	//		"2025-06-24": []user.User{
	//			{
	//				Name: "fdNick_3574",
	//			},
	//		},
	//		"2025-06-25": []user.User{
	//			{
	//				Name: "fdNick_8316",
	//			},
	//		},
	//		"2025-06-26": []user.User{
	//			{
	//				Name: "fdNick_8316",
	//			},
	//			{
	//				Name: "fdNick_0914",
	//			},
	//			{
	//				Name: "fdNick_4111",
	//			},
	//			{
	//				Name: "fdNick_6262",
	//			},
	//			{
	//				Name: "fdNick_7422",
	//			},
	//		},
	//		"2025-06-27": []user.User{
	//			{
	//				Name: "fdNick_7432",
	//			},
	//			{
	//				Name: "fdNick_7453",
	//			},
	//			{
	//				Name: "fdNick_5341",
	//			},
	//			{
	//				Name: "fdNick_2416",
	//			},
	//		},
	//		"2025-06-28": []user.User{
	//			{
	//				Name: "fdNick_6214",
	//			},
	//			{
	//				Name: "fdNick_8523",
	//			},
	//			{
	//				Name: "fdNick_4641",
	//			},
	//			{
	//				Name: "fdNick_6224",
	//			},
	//			{
	//				Name: "fdNick_7523",
	//			},
	//			{
	//				Name: "fdNick_5241",
	//			},
	//			{
	//				Name: "fdNick_6214",
	//			},
	//			{
	//				Name: "fdNick_3523",
	//			},
	//			{
	//				Name: "fdNick_5111",
	//			},
	//		},
	//	},
	//	PlanHistogram: map[string]int64{
	//		"已完成": 46,
	//		"未完成": 54,
	//	},
	//	PlanRank: []dashboard.RankInfo{},
	//	DiseaseRank: []dashboard.DiseaseRankInfo{
	//		{
	//			Username: "高血压",
	//			Count:    1433656,
	//			UserIDs: []uint{
	//				9064,
	//				9001,
	//				8151,
	//				8849,
	//				8802,
	//				8792,
	//				8281,
	//				8743,
	//				8744,
	//				7930,
	//				7793,
	//				8525,
	//				7874,
	//				7889,
	//				7899,
	//				7877,
	//				7913,
	//				7927,
	//				7890,
	//				7919,
	//				7904,
	//				8326,
	//				8048,
	//				8200,
	//				8091,
	//				8219,
	//				8250,
	//				8029,
	//				8125,
	//				8014,
	//				7882,
	//				7918,
	//				7967,
	//				7837,
	//				7950,
	//				7812,
	//				7789,
	//				7831,
	//				7809,
	//				12,
	//			},
	//		},
	//		{
	//			Username: "腹痛",
	//			Count:    238943,
	//			UserIDs: []uint{
	//				9017,
	//				8410,
	//				8820,
	//				8814,
	//				7889,
	//				8048,
	//				8250,
	//			},
	//		},
	//		{
	//			Username: "糖尿病",
	//			Count:    597357,
	//			UserIDs: []uint{
	//				8851,
	//				8835,
	//				8802,
	//				7930,
	//				7793,
	//				7815,
	//				7827,
	//				8163,
	//				8014,
	//				7876,
	//				7850,
	//				7806,
	//				7831,
	//			},
	//		},
	//		{
	//			Username: "脱发",
	//			Count:    358414,
	//			UserIDs: []uint{
	//				9061,
	//				8976,
	//				8151,
	//				8042,
	//				8744,
	//				8232,
	//				7821,
	//				7931,
	//				7793,
	//				7833,
	//				7799,
	//				7874,
	//				7815,
	//				7889,
	//				7895,
	//				7973,
	//				7883,
	//				7919,
	//				7873,
	//				8209,
	//				8396,
	//				8305,
	//				8078,
	//				7789,
	//				7524,
	//			},
	//		},
	//		{
	//			Username: "痔疮",
	//			Count:    716828,
	//			UserIDs: []uint{
	//				9062,
	//				8785,
	//				8820,
	//				8814,
	//				8452,
	//				8743,
	//				8744,
	//				7793,
	//				8080,
	//				7952,
	//				7889,
	//				7895,
	//				7927,
	//				7973,
	//				7873,
	//				8440,
	//				8060,
	//				8000,
	//				7924,
	//				7804,
	//				8153,
	//				8024,
	//				8014,
	//				7950,
	//				7802,
	//				7786,
	//			},
	//		},
	//		{
	//			Username: "尿频",
	//			Count:    716828,
	//			UserIDs: []uint{
	//				8151,
	//				8835,
	//				7944,
	//				8042,
	//				8820,
	//				8452,
	//				8743,
	//				8080,
	//				7889,
	//				7913,
	//				8060,
	//				8183,
	//				8091,
	//				7804,
	//				8024,
	//				7950,
	//				7812,
	//				7850,
	//				11,
	//			},
	//		},
	//		{
	//			Username: "冠心病",
	//			Count:    358414,
	//			UserIDs: []uint{
	//				8849,
	//				8802,
	//				8792,
	//				7930,
	//				7793,
	//				7799,
	//				7877,
	//				7974,
	//				7890,
	//				7919,
	//				7904,
	//				7827,
	//				8290,
	//				8060,
	//				8048,
	//				7975,
	//				7967,
	//				7812,
	//				7850,
	//				7809,
	//				29,
	//			},
	//		},
	//		{
	//			Username: "腰痛",
	//			Count:    955771,
	//			UserIDs: []uint{
	//				7999,
	//				7910,
	//				9017,
	//				9001,
	//				8980,
	//				8151,
	//				7943,
	//				8858,
	//				8823,
	//				8042,
	//				8820,
	//				8814,
	//				8292,
	//				8743,
	//				7821,
	//				7793,
	//				7833,
	//				8525,
	//				7861,
	//				7799,
	//				7874,
	//				7889,
	//				8481,
	//				7899,
	//				7940,
	//				7877,
	//				7915,
	//				7927,
	//				8316,
	//				7973,
	//				7919,
	//				8440,
	//				8060,
	//				8209,
	//				8048,
	//				8341,
	//				8305,
	//				8000,
	//				8029,
	//				7804,
	//				8165,
	//				8021,
	//				8031,
	//				7882,
	//				7938,
	//				7925,
	//				7967,
	//				7950,
	//				7789,
	//				7524,
	//				30,
	//			},
	//		},
	//		{
	//			Username: "神疲乏力",
	//			Count:    836299,
	//			UserIDs: []uint{
	//				9064,
	//				8151,
	//				7943,
	//				8410,
	//				8835,
	//				8042,
	//				8814,
	//				8792,
	//				8753,
	//				8744,
	//				7993,
	//				7821,
	//				7793,
	//				7861,
	//				7874,
	//				8481,
	//				8494,
	//				7899,
	//				7915,
	//				7974,
	//				8316,
	//				7827,
	//				8447,
	//				8326,
	//				7935,
	//				8060,
	//				7985,
	//				8183,
	//				8028,
	//				8395,
	//				8200,
	//				8341,
	//				7790,
	//				8219,
	//				7972,
	//				7804,
	//				8153,
	//				8165,
	//				7800,
	//				7854,
	//				7938,
	//				7967,
	//				7950,
	//				7789,
	//				7831,
	//				29,
	//			},
	//		},
	//		{
	//			Username: "血管硬化",
	//			Count:    1194714,
	//			UserIDs: []uint{
	//				9001,
	//				8151,
	//				8849,
	//				8835,
	//				7944,
	//				8042,
	//				8792,
	//				8743,
	//				7993,
	//				8232,
	//				7931,
	//				7930,
	//				7793,
	//				8437,
	//				8525,
	//				7799,
	//				7874,
	//				7952,
	//				7899,
	//				7961,
	//				7940,
	//				7915,
	//				7895,
	//				7974,
	//				7927,
	//				7890,
	//				7827,
	//				8060,
	//				7985,
	//				8048,
	//				8200,
	//				8091,
	//				8219,
	//				8163,
	//				8029,
	//				8191,
	//				7854,
	//				8014,
	//				7954,
	//				7967,
	//				7837,
	//				7950,
	//				7926,
	//				7812,
	//				7850,
	//				7809,
	//			},
	//		},
	//	},
	//	HierarchyPie: []dashboard.Pie{
	//		{
	//			Name:  "脑波训练",
	//			Value: 1672599,
	//		},
	//		{
	//			Name:  "机能训练",
	//			Value: 2150484,
	//		},
	//		{
	//			Name:  "您的配餐",
	//			Value: 477885,
	//		},
	//		{
	//			Name:  "读医栏目",
	//			Value: 955771,
	//		},
	//		{
	//			Name:  "公益项目",
	//			Value: 238943,
	//		},
	//		{
	//			Name:  "颐养天年",
	//			Value: 477885,
	//		},
	//		{
	//			Name:  "牵手夕阳",
	//			Value: 358414,
	//		},
	//		{
	//			Name:  "健康头条",
	//			Value: 119471,
	//		},
	//		{
	//			Name:  "我的",
	//			Value: 477885,
	//		},
	//		{
	//			Name:  "食谱录入（膳食指南）",
	//			Value: 358414,
	//		},
	//		{
	//			Name:  "咨询",
	//			Value: 836299,
	//		},
	//		{
	//			Name:  "体质茶",
	//			Value: 597357,
	//		},
	//		{
	//			Name:  "身体平衡",
	//			Value: 238943,
	//		},
	//		{
	//			Name:  "肌群关系",
	//			Value: 167260,
	//		},
	//		{
	//			Name:  "疼痛方案",
	//			Value: 1716828,
	//		},
	//		{
	//			Name:  "症状方案",
	//			Value: 597357,
	//		},
	//		{
	//			Name:  "筋膜平衡基础",
	//			Value: 238943,
	//		},
	//		{
	//			Name:  "简易应用",
	//			Value: 358414,
	//		},
	//		{
	//			Name:  "评估方法",
	//			Value: 238943,
	//		},
	//		{
	//			Name:  "付费课程",
	//			Value: 191154,
	//		},
	//	},
	//	ServiceHistogram: map[string]int64{
	//		"manage_num":       1433646,
	//		"no_service_count": 477886,
	//		"service_num":      955770,
	//	},
	//	Score:  0,
	//	Invite: 0,
	//	Served: 0,
	//	PlanPercent: map[string]uint{
	//		"num100": 23522,
	//		"num80":  18454,
	//		"num60":  13585,
	//		"num40":  8234,
	//		"num20":  3742,
	//		"num0":   1242,
	//	},
	//}
	return
}

func (s *BordService) GetScUserData(centreID uint) (userDashboard dashboard.User, err error) {
	today := time.Now().Format("2006-01-02")
	yesterday := time.Now().AddDate(0, 0, -1)
	var stations []system.SysUser
	if stationsErr := global.GVA_DB.Model(&system.SysUser{}).Where("authority_id = 444 AND creator = ?", centreID).Find(&stations).Error; stationsErr != nil {
		return
	}
	var ids []uint
	for _, v := range stations {
		ids = append(ids, v.ID)
	}
	var register int64
	err = global.GVA_DB.Model(&user.User{}).Count(&register).Error
	if err != nil {
		return
	}
	userDashboard.Register = register
	var vip int64
	err = global.GVA_DB.Model(&user.User{}).Where("types = 2 AND service_center_id IN (?)", ids).Count(&vip).Error
	if err != nil {
		return
	}
	userDashboard.VIP = vip
	var vipExpire int64
	err = global.GVA_DB.Model(&user.User{}).Where("types = 3 AND service_center_id IN (?)", ids).Count(&vipExpire).Error
	userDashboard.Expire = vipExpire
	// 性别
	var man int64
	var woman int64
	ageGroup := make(map[string]int64)

	var users []user.User
	err = global.GVA_DB.Find(&users, "birthday is not null AND service_center_id IN (?)", ids).Error
	if err != nil {
		return
	}
	// 年龄占比:25以下
	//         26-35
	//         36-45
	//         46-55
	//         56-65
	//         66-75
	//         76-85
	//         85以上
	for i := range users {
		if users[i].Sex == 1 {
			man++
		}
		if users[i].Sex == 2 {
			woman++
		}
		//当前时间 - users[i].Birthday 计算年龄
		age := time.Now().Year() - users[i].Birthday.Year()
		if age < 25 {
			ageGroup["25以下"]++
		} else if age >= 25 && age <= 35 {
			ageGroup["26-35"]++
		} else if age >= 36 && age <= 45 {
			ageGroup["36-45"]++
		} else if age >= 46 && age <= 55 {
			ageGroup["46-55"]++
		} else if age >= 56 && age <= 65 {
			ageGroup["56-65"]++
		} else if age >= 66 && age <= 75 {
			ageGroup["66-75"]++
		} else if age >= 76 && age <= 85 {
			ageGroup["76-85"]++
		} else if age > 85 {
			ageGroup["85以上"]++
		}
	}
	userDashboard.AgePie = []dashboard.Pie{
		{
			Name:  "25以下",
			Value: ageGroup["25以下"],
		},
		{
			Name:  "26-35",
			Value: ageGroup["26-35"],
		},
		{
			Name:  "36-45",
			Value: ageGroup["36-45"],
		},
		{
			Name:  "46-55",
			Value: ageGroup["46-55"],
		},
		{
			Name:  "56-65",
			Value: ageGroup["56-65"],
		},
		{
			Name:  "66-75",
			Value: ageGroup["66-75"],
		},
		{
			Name:  "76-85",
			Value: ageGroup["76-85"],
		},
		{
			Name:  "85以上",
			Value: ageGroup["85以上"],
		},
	}

	userDashboard.SexPie = []dashboard.Pie{
		{
			Name:  "男",
			Value: man,
		},
		{
			Name:  "女",
			Value: woman,
		},
	}

	var registerUsers []user.User
	err = global.GVA_DB.Where("created_at > ? AND service_center_id IN (?)", time.Now().AddDate(0, 0, -15), ids).Preload("HealthManager").Find(&registerUsers).Error
	if err != nil {
		return
	}
	var addLine = make(map[string][]user.User)
	// 自动填充key为最近七天的格式化
	t := time.Now()
	for i := 0; i < 15; i++ {
		date := t.AddDate(0, 0, -i).Format("2006-01-02")
		addLine[date] = make([]user.User, 0)
	}

	for i := range registerUsers {
		addLine[registerUsers[i].CreatedAt.Format("2006-01-02")] = append(addLine[registerUsers[i].CreatedAt.Format("2006-01-02")], registerUsers[i])
	}

	userDashboard.AddLine = addLine
	var foodPlan []catering.Food

	//err = global.GVA_DB.Find(&foodPlan, "date >= ? and date <= ?", today, tomorrow).Error
	err = global.GVA_DB.
		Joins("left join fd_user on fd_food.user_id = fd_user.id").
		Find(&foodPlan, "date >= ? and date <= ? and fd_user.service_center_id IN (?)", yesterday, today, ids).Error
	if err != nil {
		return
	}
	var planHistogram = make(map[string]int64)
	planHistogram["已完成"] = 0
	planHistogram["未完成"] = 0
	type kv struct {
		Key   uint
		Value int
	}
	var ss []kv
	for _, food := range foodPlan {
		schedule := getSchedule(food)
		ss = append(ss, kv{food.UserID, schedule})
		if schedule == 100 {
			planHistogram["已完成"]++
			continue
		}
		planHistogram["未完成"]++
	}
	userDashboard.PlanHistogram = planHistogram
	sort.Slice(ss, func(i, j int) bool {
		return ss[i].Value > ss[j].Value
	})
	sstop10 := ss
	if len(ss) > 10 {
		sstop10 = ss[:10]
	}
	for i := range sstop10 {
		var u user.User
		err = global.GVA_DB.First(&u, sstop10[i].Key).Error
		if err != nil {
			return
		}
		userDashboard.PlanRank = append(userDashboard.PlanRank, dashboard.RankInfo{
			Username: u.Name,
			Count:    sstop10[i].Value,
		})
	}
	var diseaseReportRecord []disease.DiseaseReportRecord
	// 按照created_at倒序排列  按照 uid 进行group 取 bzid
	err = global.GVA_DB.
		Joins("left join fd_user on fd_disease_report_record.uid = fd_user.id").
		Select("fd_disease_report_record.created_at as created_at, fd_disease_report_record.uid as uid, fd_disease_report_record.bz_ids as bz_ids").
		Group("uid").
		Order("created_at desc").
		Find(&diseaseReportRecord, "fd_user.service_center_id IN (?)", ids).Error
	if err != nil {
		return
	}
	var bzids []string
	var bzidMap = make(map[string]*dashboard.DiseaseRankInfo)
	for i := range diseaseReportRecord {
		bzArr := strings.Split(diseaseReportRecord[i].BzIDs, ",")
		for i2 := range bzArr {
			if _, ok := bzidMap[bzArr[i2]]; ok {
				bzidMap[bzArr[i2]].Count++
				bzidMap[bzArr[i2]].UserIDs = append(bzidMap[bzArr[i2]].UserIDs, diseaseReportRecord[i].Uid)
				continue
			}
			bzidMap[bzArr[i2]] = &dashboard.DiseaseRankInfo{
				Username: "",
				Count:    1,
				UserIDs:  make([]uint, 0),
			}
			bzidMap[bzArr[i2]].UserIDs = append(bzidMap[bzArr[i2]].UserIDs, diseaseReportRecord[i].Uid)
		}
		bzids = append(bzids, bzArr...)
	}
	var diseaseList []disease.Disease
	err = global.GVA_DB.Find(&diseaseList, "id in (?)", bzids).Error
	for i := range diseaseList {
		sid := strconv.Itoa(int(diseaseList[i].ID))
		if _, ok := bzidMap[sid]; ok {
			bzidMap[sid].Username = diseaseList[i].Name
		}
	}
	for _, v := range bzidMap {

		userDashboard.DiseaseRank = append(userDashboard.DiseaseRank, *v)
	}

	var fdVideoArticle []hierarchy.FdArticle
	var fdGraphicArticle []hierarchy.FdArticle
	var fdAudioArticle []hierarchy.FdArticle
	var fdArticle []hierarchy.FdArticle
	var levelCount = make(map[int]int64)
	var HierarchyPie []dashboard.Pie
	err = global.GVA_DB.Model(&hierarchy.FdArticleVideo{}).Find(&fdVideoArticle).Error
	err = global.GVA_DB.Model(&hierarchy.FdArticleGraphic{}).Find(&fdGraphicArticle).Error
	err = global.GVA_DB.Model(&hierarchy.FdArticleAudio{}).Find(&fdAudioArticle).Error
	fdArticle = append(fdArticle, fdVideoArticle...)
	fdArticle = append(fdArticle, fdGraphicArticle...)
	fdArticle = append(fdArticle, fdAudioArticle...)
	for i := range fdArticle {
		if fdArticle[i].LevelOneID != nil {
			levelCount[*fdArticle[i].LevelOneID]++
		}
	}
	var levelOne []hierarchy.LevelOne
	err = global.GVA_DB.Find(&levelOne).Error
	for i := range levelOne {
		HierarchyPie = append(HierarchyPie, dashboard.Pie{
			Name:  levelOne[i].Value,
			Value: levelCount[int(levelOne[i].ID)],
		})
	}
	userDashboard.HierarchyPie = HierarchyPie

	// 统计在管人数
	var memberCount int64
	err = global.GVA_DB.Model(&user.User{}).Where("types = 2 AND service_center_id IN (?)", ids).Count(&memberCount).Error
	startTime := yesterday.Format("2006-01-02")
	endTime := time.Now().Format("2006-01-02")
	// 统计服务人数
	var serviceCount int64
	var healthManagers []manager.FdHealthManager
	if healthManagersErr := global.GVA_DB.Model(&manager.FdHealthManager{}).Where("store_id IN (?)", ids).Find(&healthManagers).Error; healthManagersErr != nil {
		return
	}
	var HmIDs []uint
	for _, v := range healthManagers {
		HmIDs = append(HmIDs, v.HmId)
	}
	err = global.GVA_DB.Model(&manager.MessageRemind{}).
		Joins("left join fd_health_manager on fd_message_remind.hm_id = fd_health_manager.hm_id").
		Where("fd_message_remind.created_at BETWEEN ? AND ? AND fd_message_remind.hm_id IN (?)", startTime, endTime, HmIDs).Count(&serviceCount).Error
	userDashboard.ServiceHistogram = map[string]int64{
		"manage_num":       memberCount,
		"service_num":      serviceCount,
		"no_service_count": memberCount - serviceCount, // 直接减法更快
	}

	// 统计方案完成进度数量(总)
	var percents []catering.Food
	err = global.GVA_DB.Find(&percents).Error
	var num100 uint
	var num80 uint
	var num60 uint
	var num40 uint
	var num20 uint
	var num0 uint
	for i := range percents {
		if percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Brain != nil && percents[i].Sport != nil {
			num100++
		} else if (percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Brain != nil) ||
			(percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Sport != nil) ||
			(percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Brain != nil && percents[i].Sport != nil) ||
			(percents[i].Breakfast != nil && percents[i].Dinner != nil && percents[i].Brain != nil && percents[i].Sport != nil) ||
			(percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Brain != nil && percents[i].Sport != nil) {
			num80++
		} else if (percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Dinner != nil) ||
			(percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Brain != nil) ||
			(percents[i].Breakfast != nil && percents[i].Lunch != nil && percents[i].Sport != nil) ||
			(percents[i].Breakfast != nil && percents[i].Dinner != nil && percents[i].Brain != nil) ||
			(percents[i].Breakfast != nil && percents[i].Dinner != nil && percents[i].Sport != nil) ||
			(percents[i].Breakfast != nil && percents[i].Brain != nil && percents[i].Sport != nil) ||
			(percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Brain != nil) ||
			(percents[i].Lunch != nil && percents[i].Dinner != nil && percents[i].Sport != nil) ||
			(percents[i].Lunch != nil && percents[i].Brain != nil && percents[i].Sport != nil) ||
			(percents[i].Dinner != nil && percents[i].Brain != nil && percents[i].Sport != nil) {
			num60++
		} else if (percents[i].Breakfast != nil && percents[i].Lunch != nil) ||
			(percents[i].Breakfast != nil && percents[i].Dinner != nil) ||
			(percents[i].Breakfast != nil && percents[i].Brain != nil) ||
			(percents[i].Breakfast != nil && percents[i].Sport != nil) ||
			(percents[i].Lunch != nil && percents[i].Dinner != nil) ||
			(percents[i].Lunch != nil && percents[i].Brain != nil) ||
			(percents[i].Lunch != nil && percents[i].Sport != nil) ||
			(percents[i].Dinner != nil && percents[i].Brain != nil) ||
			(percents[i].Dinner != nil && percents[i].Sport != nil) ||
			(percents[i].Brain != nil && percents[i].Sport != nil) {
			num40++
		} else if (percents[i].Breakfast != nil) || (percents[i].Lunch != nil) || (percents[i].Dinner != nil) || (percents[i].Brain != nil) || (percents[i].Sport != nil) {
			num20++
		} else {
			num0++
		}
	}
	userDashboard.PlanPercent = map[string]uint{
		"num100": num100,
		"num80":  num80,
		"num60":  num60,
		"num40":  num40,
		"num20":  num20,
		"num0":   num0,
	}
	return
}

// User 获取全部用户数据大屏【服务站】
func (s *BordService) User(id uint) (userDashboard dashboard.User, err error) {
	today := time.Now().Format("2006-01-02")
	yesterday := time.Now().AddDate(0, 0, -1)
	var register int64
	err = global.GVA_DB.Model(&user.User{}).Where("service_center_id = ?", id).Count(&register).Error
	if err != nil {
		return
	}
	userDashboard.Register = register
	var vip int64
	err = global.GVA_DB.Model(&user.User{}).Where("types = 2 and service_center_id = ?", id).Count(&vip).Error
	if err != nil {
		return
	}
	userDashboard.VIP = vip
	var vipExpire int64
	err = global.GVA_DB.Model(&user.User{}).Where("types = 3 and service_center_id = ?", id).Count(&vipExpire).Error
	userDashboard.Expire = vipExpire
	// 性别
	var man int64
	var woman int64
	ageGroup := make(map[string]int64)

	var users []user.User
	err = global.GVA_DB.Find(&users, "birthday is not null AND service_center_id = ?", id).Error
	if err != nil {
		return
	}
	// 年龄占比:25以下
	//         26-35
	//         36-45
	//         46-55
	//         56-65
	//         66-75
	//         76-85
	//         85以上
	for i := range users {
		if users[i].Sex == 1 {
			man++
		}
		if users[i].Sex == 2 {
			woman++
		}
		//当前时间 - users[i].Birthday 计算年龄
		age := time.Now().Year() - users[i].Birthday.Year()
		if age < 25 {
			ageGroup["25以下"]++
		} else if age >= 25 && age <= 35 {
			ageGroup["26-35"]++
		} else if age >= 36 && age <= 45 {
			ageGroup["36-45"]++
		} else if age >= 46 && age <= 55 {
			ageGroup["46-55"]++
		} else if age >= 56 && age <= 65 {
			ageGroup["56-65"]++
		} else if age >= 66 && age <= 75 {
			ageGroup["66-75"]++
		} else if age >= 76 && age <= 85 {
			ageGroup["76-85"]++
		} else if age > 85 {
			ageGroup["85以上"]++
		}
	}
	userDashboard.AgePie = []dashboard.Pie{
		{
			Name:  "25以下",
			Value: ageGroup["25以下"],
		},
		{
			Name:  "26-35",
			Value: ageGroup["26-35"],
		},
		{
			Name:  "36-45",
			Value: ageGroup["36-45"],
		},
		{
			Name:  "46-55",
			Value: ageGroup["46-55"],
		},
		{
			Name:  "56-65",
			Value: ageGroup["56-65"],
		},
		{
			Name:  "66-75",
			Value: ageGroup["66-75"],
		},
		{
			Name:  "76-85",
			Value: ageGroup["76-85"],
		},
		{
			Name:  "85以上",
			Value: ageGroup["85以上"],
		},
	}

	userDashboard.SexPie = []dashboard.Pie{
		{
			Name:  "男",
			Value: man,
		},
		{
			Name:  "女",
			Value: woman,
		},
	}

	var registerUsers []user.User
	err = global.GVA_DB.Where("created_at > ? AND service_center_id = ?", time.Now().AddDate(0, 0, -15), id).Preload("HealthManager").Find(&registerUsers).Error
	if err != nil {
		return
	}
	var addLine = make(map[string][]user.User)
	// 自动填充key为最近七天的格式化
	t := time.Now()
	for i := 0; i < 15; i++ {
		date := t.AddDate(0, 0, -i).Format("2006-01-02")
		addLine[date] = make([]user.User, 0)
	}

	for i := range registerUsers {
		addLine[registerUsers[i].CreatedAt.Format("2006-01-02")] = append(addLine[registerUsers[i].CreatedAt.Format("2006-01-02")], registerUsers[i])
	}

	userDashboard.AddLine = addLine
	var foodPlan []catering.Food

	//err = global.GVA_DB.Find(&foodPlan, "date >= ? and date <= ?", today, tomorrow).Error
	err = global.GVA_DB.
		Joins("left join fd_user on fd_food.user_id = fd_user.id").
		Find(&foodPlan, "date >= ? and date <= ? and fd_user.service_center_id = ?", yesterday, today, id).Error
	if err != nil {
		return
	}
	var planHistogram = make(map[string]int64)
	planHistogram["已完成"] = 0
	planHistogram["未完成"] = 0
	type kv struct {
		Key   uint
		Value int
	}
	var ss []kv
	for _, food := range foodPlan {
		schedule := getSchedule(food)
		ss = append(ss, kv{food.UserID, schedule})
		if schedule == 100 {
			planHistogram["已完成"]++
			continue
		}
		planHistogram["未完成"]++
	}
	userDashboard.PlanHistogram = planHistogram
	sort.Slice(ss, func(i, j int) bool {
		return ss[i].Value > ss[j].Value
	})
	sstop10 := ss
	if len(ss) > 10 {
		sstop10 = ss[:10]
	}
	for i := range sstop10 {
		var u user.User
		err = global.GVA_DB.First(&u, sstop10[i].Key).Error
		if err != nil {
			return
		}
		userDashboard.PlanRank = append(userDashboard.PlanRank, dashboard.RankInfo{
			Username: u.Name,
			Count:    sstop10[i].Value,
		})
	}
	var diseaseReportRecord []disease.DiseaseReportRecord
	// 按照created_at倒序排列  按照 uid 进行group 取 bzid
	err = global.GVA_DB.
		Joins("left join fd_user on fd_disease_report_record.uid = fd_user.id").
		Select("fd_disease_report_record.created_at as created_at, fd_disease_report_record.uid as uid, fd_disease_report_record.bz_ids as bz_ids").
		Group("uid").
		Order("created_at desc").
		Find(&diseaseReportRecord, "fd_user.service_center_id = ?", id).Error
	if err != nil {
		return
	}
	var bzids []string
	var bzidMap = make(map[string]*dashboard.DiseaseRankInfo)
	for i := range diseaseReportRecord {
		bzArr := strings.Split(diseaseReportRecord[i].BzIDs, ",")
		for i2 := range bzArr {
			if _, ok := bzidMap[bzArr[i2]]; ok {
				bzidMap[bzArr[i2]].Count++
				bzidMap[bzArr[i2]].UserIDs = append(bzidMap[bzArr[i2]].UserIDs, diseaseReportRecord[i].Uid)
				continue
			}
			bzidMap[bzArr[i2]] = &dashboard.DiseaseRankInfo{
				Username: "",
				Count:    1,
				UserIDs:  make([]uint, 0),
			}
			bzidMap[bzArr[i2]].UserIDs = append(bzidMap[bzArr[i2]].UserIDs, diseaseReportRecord[i].Uid)
		}
		bzids = append(bzids, bzArr...)
	}
	var diseaseList []disease.Disease
	err = global.GVA_DB.Find(&diseaseList, "id in (?)", bzids).Error
	for i := range diseaseList {
		sid := strconv.Itoa(int(diseaseList[i].ID))
		if _, ok := bzidMap[sid]; ok {
			bzidMap[sid].Username = diseaseList[i].Name
		}
	}
	for _, v := range bzidMap {
		userDashboard.DiseaseRank = append(userDashboard.DiseaseRank, *v)
	}

	var fdVideoArticle []hierarchy.FdArticle
	var fdGraphicArticle []hierarchy.FdArticle
	var fdAudioArticle []hierarchy.FdArticle
	var fdArticle []hierarchy.FdArticle
	var levelCount = make(map[int]int64)
	var HierarchyPie []dashboard.Pie
	err = global.GVA_DB.Model(&hierarchy.FdArticleVideo{}).Find(&fdVideoArticle).Error
	err = global.GVA_DB.Model(&hierarchy.FdArticleGraphic{}).Find(&fdGraphicArticle).Error
	err = global.GVA_DB.Model(&hierarchy.FdArticleAudio{}).Find(&fdAudioArticle).Error
	fdArticle = append(fdArticle, fdVideoArticle...)
	fdArticle = append(fdArticle, fdGraphicArticle...)
	fdArticle = append(fdArticle, fdAudioArticle...)
	for i := range fdArticle {
		if fdArticle[i].LevelOneID != nil {
			levelCount[*fdArticle[i].LevelOneID]++
		}
	}
	var levelOne []hierarchy.LevelOne
	err = global.GVA_DB.Find(&levelOne).Error
	for i := range levelOne {
		HierarchyPie = append(HierarchyPie, dashboard.Pie{
			Name:  levelOne[i].Value,
			Value: levelCount[int(levelOne[i].ID)],
		})
	}
	userDashboard.HierarchyPie = HierarchyPie

	// 统计在管人数
	var memberCount int64
	err = global.GVA_DB.Model(&user.User{}).Where("types = 2 AND service_center_id = ?", id).Count(&memberCount).Error
	startTime := yesterday.Format("2006-01-02")
	endTime := time.Now().Format("2006-01-02")
	// 统计服务人数
	var serviceCount int64
	var healthManagers []manager.FdHealthManager
	if healthManagersErr := global.GVA_DB.Model(&manager.FdHealthManager{}).Where("store_id IN (?)", id).Find(&healthManagers).Error; healthManagersErr != nil {
		return
	}
	var HmIDs []uint
	for _, v := range healthManagers {
		HmIDs = append(HmIDs, v.HmId)
	}
	err = global.GVA_DB.Model(&manager.MessageRemind{}).
		Joins("left join fd_health_manager on fd_message_remind.hm_id = fd_health_manager.hm_id").
		Where("fd_message_remind.created_at BETWEEN ? AND ? AND fd_message_remind.hm_id IN (?)", startTime, endTime, HmIDs).Count(&serviceCount).Error
	userDashboard.ServiceHistogram = map[string]int64{
		"manage_num":       memberCount,
		"service_num":      serviceCount,
		"no_service_count": memberCount - serviceCount, // 直接减法更快
	}
	//userDashboard = dashboard.User{
	//	Register: 18731,
	//	Served:   0,
	//	Invite:   0,
	//	Score:    0,
	//	Expire:   7492,
	//	VIP:      11239,
	//	AddLine: map[string][]user.User{
	//		"2023-05-01": []user.User{
	//			{
	//				Name: "fdNick_0511",
	//			},
	//		},
	//		"2025-06-15": []user.User{
	//			{
	//				Name: "fdNick_4132",
	//			},
	//		},
	//		"2025-06-16": []user.User{
	//			{
	//				Name: "fdNick_0541",
	//			},
	//		},
	//		"2025-06-17": []user.User{
	//			{
	//				Name: "fdNick_6213",
	//			},
	//		},
	//		"2025-06-18": []user.User{
	//			{
	//				Name: "fdNick_8383",
	//			},
	//			{
	//				Name: "fdNick_1006",
	//			},
	//		},
	//		"2025-06-19": []user.User{
	//			{
	//				Name: "fdNick_0114",
	//			},
	//		},
	//		"2025-06-20": []user.User{
	//			{
	//				Name: "fdNick_0841",
	//			},
	//		},
	//		"2025-06-21": []user.User{
	//			{
	//				Name: "fdNick_0241",
	//			},
	//		},
	//		"2025-06-22": []user.User{
	//			{
	//				Name: "fdNick_6341",
	//			},
	//		},
	//		"2025-06-23": []user.User{
	//			{
	//				Name: "fdNick_7421",
	//			},
	//			{
	//				Name: "fdNick_9043",
	//			},
	//			{
	//				Name: "fdNick_3654",
	//			},
	//			{
	//				Name: "fdNick_1316",
	//			},
	//		},
	//		"2025-06-24": []user.User{
	//			{
	//				Name: "fdNick_3574",
	//			},
	//		},
	//		"2025-06-25": []user.User{
	//			{
	//				Name: "fdNick_8316",
	//			},
	//		},
	//		"2025-06-26": []user.User{
	//			{
	//				Name: "fdNick_8316",
	//			},
	//			{
	//				Name: "fdNick_0914",
	//			},
	//			{
	//				Name: "fdNick_4111",
	//			},
	//			{
	//				Name: "fdNick_6262",
	//			},
	//			{
	//				Name: "fdNick_7422",
	//			},
	//		},
	//		"2025-06-27": []user.User{
	//			{
	//				Name: "fdNick_7432",
	//			},
	//			{
	//				Name: "fdNick_7453",
	//			},
	//			{
	//				Name: "fdNick_5341",
	//			},
	//			{
	//				Name: "fdNick_2416",
	//			},
	//		},
	//		"2025-06-28": []user.User{
	//			{
	//				Name: "fdNick_6214",
	//			},
	//			{
	//				Name: "fdNick_8523",
	//			},
	//			{
	//				Name: "fdNick_5141",
	//			},
	//		},
	//	},
	//	AgePie: []dashboard.Pie{
	//		{
	//			Name:  "25以下",
	//			Value: 65,
	//		},
	//		{
	//			Name:  "26-35",
	//			Value: 217,
	//		},
	//		{
	//			Name:  "36-45",
	//			Value: 325,
	//		},
	//		{
	//			Name:  "46-55",
	//			Value: 1815,
	//		},
	//		{
	//			Name:  "56-65",
	//			Value: 3696,
	//		},
	//		{
	//			Name:  "66-75",
	//			Value: 7528,
	//		},
	//		{
	//			Name:  "76-85",
	//			Value: 3917,
	//		},
	//		{
	//			Name:  "85以上",
	//			Value: 1168,
	//		},
	//	},
	//	SexPie: []dashboard.Pie{
	//		{
	//			Name:  "男",
	//			Value: 5620,
	//		},
	//		{
	//			Name:  "女",
	//			Value: 13111,
	//		},
	//	},
	//	DiseaseRank: []dashboard.DiseaseRankInfo{
	//		{
	//			Username: "眼睑有硬核",
	//			Count:    1025,
	//			UserIDs: []uint{
	//				7889,
	//			},
	//		},
	//		{
	//			Username: "牙龈出血",
	//			Count:    1000,
	//			UserIDs: []uint{
	//				7895,
	//			},
	//		},
	//		{
	//			Username: "健忘",
	//			Count:    968,
	//			UserIDs: []uint{
	//				8685,
	//				7944,
	//				8792,
	//				7939,
	//				7931,
	//				7930,
	//				8437,
	//				8525,
	//				7874,
	//				7889,
	//				7899,
	//				7877,
	//				7915,
	//				7895,
	//				7974,
	//				7927,
	//				8316,
	//				7919,
	//				7873,
	//				7827,
	//				7854,
	//				7975,
	//				7954,
	//				7967,
	//				7950,
	//				7926,
	//			},
	//		},
	//		{
	//			Username: "牙痛",
	//			Count:    886,
	//			UserIDs: []uint{
	//				7944,
	//				7793,
	//				7889,
	//				7890,
	//				7967,
	//			},
	//		},
	//		{
	//			Username: "甲状腺肿",
	//			Count:    862,
	//			UserIDs: []uint{
	//				8232,
	//				7931,
	//				7930,
	//				7895,
	//				7927,
	//				7890,
	//				7919,
	//			},
	//		},
	//		{
	//			Username: "前列腺病",
	//			Count:    817,
	//			UserIDs: []uint{
	//				7944,
	//				7931,
	//				7874,
	//			},
	//		},
	//		{
	//			Username: "尿路感染",
	//			Count:    805,
	//			UserIDs: []uint{
	//				8792,
	//				7930,
	//				7950,
	//			},
	//		},
	//		{
	//			Username: "腰膝冷痛",
	//			Count:    785,
	//			UserIDs: []uint{
	//				7939,
	//				8525,
	//				7874,
	//				7899,
	//				7915,
	//				7927,
	//				7919,
	//				7938,
	//				7967,
	//			},
	//		},
	//		{
	//			Username: "自汗",
	//			Count:    652,
	//			UserIDs: []uint{
	//				7793,
	//				7899,
	//				7884,
	//				7927,
	//				7890,
	//				7973,
	//				7883,
	//				7926,
	//			},
	//		},
	//		{
	//			Username: "高血压",
	//			Count:    236,
	//			UserIDs: []uint{
	//				7919,
	//			},
	//		},
	//	},
	//	PlanHistogram: map[string]int64{
	//		"已完成": 12562,
	//		"未完成": 6169,
	//	},
	//	PlanRank: nil,
	//	HierarchyPie: []dashboard.Pie{
	//		{
	//			Name:  "脑波训练",
	//			Value: 672599,
	//		},
	//		{
	//			Name:  "机能训练",
	//			Value: 150484,
	//		},
	//		{
	//			Name:  "您的配餐",
	//			Value: 77885,
	//		},
	//		{
	//			Name:  "读医栏目",
	//			Value: 55771,
	//		},
	//		{
	//			Name:  "公益项目",
	//			Value: 38943,
	//		},
	//		{
	//			Name:  "颐养天年",
	//			Value: 77885,
	//		},
	//		{
	//			Name:  "牵手夕阳",
	//			Value: 58414,
	//		},
	//		{
	//			Name:  "健康头条",
	//			Value: 19471,
	//		},
	//		{
	//			Name:  "我的",
	//			Value: 77885,
	//		},
	//		{
	//			Name:  "食谱录入（膳食指南）",
	//			Value: 58414,
	//		},
	//		{
	//			Name:  "咨询",
	//			Value: 36299,
	//		},
	//		{
	//			Name:  "体质茶",
	//			Value: 97357,
	//		},
	//		{
	//			Name:  "身体平衡",
	//			Value: 38943,
	//		},
	//		{
	//			Name:  "肌群关系",
	//			Value: 67260,
	//		},
	//		{
	//			Name:  "疼痛方案",
	//			Value: 716828,
	//		},
	//		{
	//			Name:  "症状方案",
	//			Value: 97357,
	//		},
	//		{
	//			Name:  "筋膜平衡基础",
	//			Value: 38943,
	//		},
	//		{
	//			Name:  "简易应用",
	//			Value: 58414,
	//		},
	//		{
	//			Name:  "评估方法",
	//			Value: 38943,
	//		},
	//		{
	//			Name:  "付费课程",
	//			Value: 91154,
	//		},
	//	},
	//	ServiceHistogram: map[string]int64{
	//		"manage_num":       3210,
	//		"no_service_count": 2734,
	//		"service_num":      466,
	//	},
	//}
	return
}

func getSchedule(food catering.Food) (schedule int) {
	if food.Breakfast != nil && *food.Breakfast != 0 {
		schedule += 20
	}
	if food.Lunch != nil && *food.Lunch != 0 {
		schedule += 20
	}
	if food.Dinner != nil && *food.Dinner != 0 {
		schedule += 20
	}
	//if food.Tea != nil && *food.Tea != 0 {
	//	schedule += 1
	//}
	if food.Brain != nil && *food.Brain != 0 {
		schedule += 20
	}
	if food.Sport != nil && *food.Sport != 0 {
		schedule += 20
	}
	return
}

func (s *BordService) Steward(id uint) (stewardDashboard dashboard.Steward, err error) {
	var register int64
	err = global.GVA_DB.Model(&manager.FdHealthManager{}).Where("is_register = ? and store_id = ?", true, id).Count(&register).Error
	if err != nil {
		return
	}
	stewardDashboard.Application = register
	var audit int64
	err = global.GVA_DB.Model(&manager.FdHealthManager{}).Where("is_audit = ? and store_id = ?", true, id).Count(&audit).Error
	if err != nil {
		return
	}
	stewardDashboard.Incumbency = audit
	// 计算健管师界别分组
	var managers []manager.FdHealthManager
	err = global.GVA_DB.Find(&managers, "store_id = ?", id).Error
	if err != nil {
		return
	}
	var primary int64
	var intermediate int64
	var senior int64
	for i := range managers {
		if managers[i].Level == 0 {
			primary++
		}
		if managers[i].Level == 1 {
			intermediate++
		}
		if managers[i].Level == 2 {
			senior++
		}
	}
	stewardDashboard.LevelProportion = []dashboard.Pie{
		{
			Name:  "初级",
			Value: primary,
		},
		{
			Name:  "中级",
			Value: intermediate,
		},
		{
			Name:  "高级",
			Value: senior,
		},
	}
	//用 direct_num + indirect_num 倒叙排列取前10
	var top10 []manager.FdHealthManager
	err = global.GVA_DB.Order("direct_num + indirect_num desc").Limit(10).Find(&top10, "store_id = ?", id).Error
	if err != nil {
		return
	}
	for i := range top10 {
		stewardDashboard.RegistrantsRank = append(stewardDashboard.RegistrantsRank, dashboard.RankInfo{
			Username: top10[i].Name,
			Count:    *top10[i].DirectNum + *top10[i].IndirectNum,
		})
	}
	//用 score 倒叙排列取前10
	var top10Score []manager.FdHealthManager
	err = global.GVA_DB.Order("score desc").Limit(10).Find(&top10Score, "store_id = ?", id).Error
	if err != nil {
		return
	}
	for i := range top10Score {
		score := 0
		if top10Score[i].Score != 0 {
			score = int(top10Score[i].Score)
		}

		stewardDashboard.ExcellentRank = append(stewardDashboard.ExcellentRank, dashboard.RankInfo{
			Username: top10Score[i].Name,
			Count:    score,
		})
	}

	// 当日服务人数 倒叙排列取前10
	var ServiceUser []dashboard.RankInfo
	yesterday := time.Now().AddDate(0, 0, -1)
	startTime := yesterday.Format("2006-01-02")
	endTime := time.Now().Format("2006-01-02")
	err = global.GVA_DB.Model(&system.SysUser{}).
		Select("b.name AS username, COUNT( DISTINCT c.user_id ) AS count, GROUP_CONCAT(c.user_id) AS IDs").
		Joins("LEFT JOIN `fd_health_manager` AS b ON sys_users.id = b.store_id").
		Joins("LEFT JOIN `fd_message_remind` AS c ON b.hm_id = c.hm_id ").
		Where("c.created_at BETWEEN ? AND ? AND sys_users.id = ?", startTime, endTime, id).
		Group("b.hm_id").Order("count DESC").Limit(10).Scan(&ServiceUser).Error
	stewardDashboard.ServedRank = ServiceUser
	//stewardDashboard = dashboard.Steward{
	//	Application: 168,
	//	Incumbency:  114,
	//	LevelProportion: []dashboard.Pie{
	//		{
	//			Name:  "初级",
	//			Value: 53,
	//		},
	//		{
	//			Name:  "中级",
	//			Value: 28,
	//		},
	//		{
	//			Name:  "高级",
	//			Value: 19,
	//		},
	//	},
	//	RegistrantsRank: []dashboard.RankInfo{
	//		{
	//			Username: "晓燕",
	//			Count:    279,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "卡卡",
	//			Count:    261,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "王佳露",
	//			Count:    257,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "张平",
	//			Count:    251,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "李烨子",
	//			Count:    232,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "刘璇",
	//			Count:    211,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "姜民丽",
	//			Count:    206,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "任晓丽",
	//			Count:    187,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "李天骄",
	//			Count:    183,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "杜鹃",
	//			Count:    162,
	//			IDs:      "",
	//		},
	//	},
	//	ServedRank: []dashboard.RankInfo{
	//		{
	//			Username: "张平",
	//			Count:    194,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "李烨子",
	//			Count:    182,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "姜民丽",
	//			Count:    173,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "杜鹃",
	//			Count:    162,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "刘璇",
	//			Count:    143,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "任晓丽",
	//			Count:    113,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "王佳露",
	//			Count:    105,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "李天骄",
	//			Count:    103,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "晓燕",
	//			Count:    98,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "卡卡",
	//			Count:    76,
	//			IDs:      "",
	//		},
	//	},
	//	ExcellentRank: []dashboard.RankInfo{
	//		{
	//			Username: "杜鹃",
	//			Count:    150,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "姜民丽",
	//			Count:    147,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "李烨子",
	//			Count:    121,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "张平",
	//			Count:    115,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "刘璇",
	//			Count:    97,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "任晓丽",
	//			Count:    95,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "王佳露",
	//			Count:    86,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "李天骄",
	//			Count:    75,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "晓燕",
	//			Count:    64,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "卡卡",
	//			Count:    59,
	//			IDs:      "",
	//		},
	//	},
	//}
	return
}

// GetAllStewardData 获取全部健管师数据大屏【超管】
func (s *BordService) GetAllStewardData() (stewardDashboard dashboard.Steward, err error) {
	var register int64
	err = global.GVA_DB.Model(&manager.FdHealthManager{}).Where("is_register = ?", true).Count(&register).Error
	if err != nil {
		return
	}
	stewardDashboard.Application = register
	var audit int64
	err = global.GVA_DB.Model(&manager.FdHealthManager{}).Where("is_audit = ?", true).Count(&audit).Error
	if err != nil {
		return
	}
	stewardDashboard.Incumbency = audit
	// 计算健管师界别分组
	var managers []manager.FdHealthManager
	err = global.GVA_DB.Find(&managers).Error
	if err != nil {
		return
	}
	var primary int64
	var intermediate int64
	var senior int64
	for i := range managers {
		if managers[i].Level == 0 {
			primary++
		}
		if managers[i].Level == 1 {
			intermediate++
		}
		if managers[i].Level == 2 {
			senior++
		}
	}
	stewardDashboard.LevelProportion = []dashboard.Pie{
		{
			Name:  "初级",
			Value: primary,
		},
		{
			Name:  "中级",
			Value: intermediate,
		},
		{
			Name:  "高级",
			Value: senior,
		},
	}
	//用 direct_num + indirect_num 倒叙排列取前10
	var top10 []manager.FdHealthManager
	err = global.GVA_DB.Order("direct_num + indirect_num desc").Limit(10).Find(&top10).Error
	if err != nil {
		return
	}
	var RegistrantsUser dashboard.RankInfo
	// 注册人数排行
	for i := range top10 {
		global.GVA_DB.Model(&user.User{}).Select("GROUP_CONCAT(id) AS IDs").Where("steward_id = ?", top10[i].HmId).Scan(&RegistrantsUser)
		stewardDashboard.RegistrantsRank = append(stewardDashboard.RegistrantsRank, dashboard.RankInfo{
			Username: top10[i].Name,
			Count:    *top10[i].DirectNum + *top10[i].IndirectNum,
			IDs:      RegistrantsUser.IDs,
		})
	}
	//用 score 倒叙排列取前10
	var top10Score []manager.FdHealthManager
	err = global.GVA_DB.Order("score desc").Limit(10).Find(&top10Score).Error
	if err != nil {
		return
	}
	for i := range top10Score {
		score := 0
		if top10Score[i].Score != 0 {
			score = int(top10Score[i].Score)
		}
		stewardDashboard.ExcellentRank = append(stewardDashboard.ExcellentRank, dashboard.RankInfo{
			Username: top10Score[i].Name,
			Count:    score,
		})
	}
	// 统计服务人数 倒叙排列取前10
	var ServiceUser []dashboard.RankInfo
	yesterday := time.Now().AddDate(0, 0, -1)
	startTime := yesterday.Format("2006-01-02")
	endTime := time.Now().Format("2006-01-02")
	err = global.GVA_DB.Model(&manager.MessageRemind{}).
		Select("fd_health_manager.name AS username, COUNT( DISTINCT user_id ) AS count, GROUP_CONCAT(user_id) AS IDs").
		Joins("LEFT JOIN fd_health_manager on fd_message_remind.hm_id = fd_health_manager.hm_id").
		Where("fd_message_remind.created_at BETWEEN ? AND ?", startTime, endTime).
		Group("fd_health_manager.hm_id").Order("count DESC").Limit(10).Scan(&ServiceUser).Error
	stewardDashboard.ServedRank = ServiceUser
	//stewardDashboard = dashboard.Steward{
	//	Application: 18916,
	//	Incumbency:  11947,
	//	LevelProportion: []dashboard.Pie{
	//		{
	//			Name:  "初级",
	//			Value: 5376,
	//		},
	//		{
	//			Name:  "中级",
	//			Value: 4182,
	//		},
	//		{
	//			Name:  "高级",
	//			Value: 2389,
	//		},
	//	},
	//	RegistrantsRank: []dashboard.RankInfo{
	//		{
	//			Username: "董美香",
	//			Count:    314,
	//			IDs:      "5,30,35,7766,7768,7769,7770,7771,7772,7773,7774,7775,7815,7858,7879,7922,7934,7941,7970,7989,8021,8041,8043,8055,8070,8093,8113,8126,8127,8128,8129,8130,8131,8133,8134,8135,8137,8138,8139,8140,8141,8142,8143,8144,8145,8146,8147,8148,8149,8150,8152,8155,8158,8160,8161,8164,8165,8166,8167,8171,8172,8173,8174,8175,8176,8177,8178,8179,8180,8181,8182,8183,8184,8185,8186,8187,8188,8191,8192,8193,8195,8197,8198,8199,8200,8201,8202,8206,8209,8210,8211,8213,8214,8215,8216,8219,8220,8221,8222,8223,8224,8225,8226,8227,8231,8233,8234,8236,8237,8238,8242,8243,8244,8245,8246,8247,8248,8249,8250,8252,8253,8254,8255,8256,8257,8261,8262,8265,8266,8267,8269,8270,8273,8274,8275,8276,8277,8279,8280,8281,8282,8283,8284,8286,8287,8289,8291,8294,8295,8299,8301,8303,8304,8307,8308,8309,8312,8313,8314,8315,8319,8320,8325,8333,8339,8340,8343,8344,8345,8349,8350,8351,8352,8359,8360,8361,8362,8363,8364,8365,8366,8368,8372,8373,8376,8377,8378,8380,8383,8384,8385,8386,8387,8389,8392,8399,8401,8402,8404,8406,8412,8413,8414,8415,8416,8418,8419,8420,8421,8423,8425,8428,8431,8436,8440,8441,8442,8446,8449,8463,8465,8466,8468,8475,8476,8481,8483,8489,8510,8527,8536,8542,8555,8589,8591,8595,8608,8612,8614,8643,8663,8687,8689,8692,8704,8712,8713,8719,8729,8737,8739,8742,8747,8756,8761,8770,8772,8791,8799,8805,8829,8830,8833,8835,8839,8843,8844,8846,8847,8849,8854,8855,8857,8864,8866,8867,8877,8878,8885,8889,8890,8897,8898,8899,8902,8910,8911,8917,8919,8920,8922,8925,8928,8931,8946,8948,8949,8950,8955,8956,8958,8962,8967,8968,8969,8970,8972,8975,8976,8978,8980,8981,8982,8983,8985,8986,8987,8988,8989,8991,8993,8994,8995,9003,9008,9009,9014,9015,9017,9024,9025,9029,9031,9033,9038,9039,9041,9043,9044,9046,9051,9056,9057,9059,9064,9071,9075,9079,9081,9084,9085,9087,9093,9094,9096,9098,9099,9100,9101,9103,9105,9106,9107,9110,9113,9114,9115,9117,9119,9120,9124,9125,9126,9127,9128",
	//		},
	//		{
	//			Username: "夏秀莲",
	//			Count:    296,
	//			IDs:      "7780,7993,7994,7995,7996,7997,7998,7999,8000,8001,8002,8005,8007,8008,8009,8010,8011,8013,8015,8016,8017,8020,8023,8024,8025,8026,8027,8028,8029,8030,8031,8032,8033,8035,8036,8039,8040,8042,8044,8046,8047,8049,8051,8053,8057,8058,8059,8060,8061,8062,8063,8066,8067,8068,8069,8071,8072,8073,8074,8076,8078,8079,8080,8082,8085,8086,8087,8090,8091,8092,8094,8095,8097,8099,8100,8101,8103,8104,8105,8106,8107,8109,8110,8111,8114,8116,8119,8120,8121,8125,8153,8154,8156,8157,8162,8163,8168,8169,8194,8196,8204,8207,8239,8240,8241,8251,8258,8260,8271,8310,8311,8318,8324,8327,8328,8336,8375,8379,8398,8407,8411,8426,8443,8451,8456,8467,8470,8472,8486,8493,8498,8512,8535,8549,8601,8646,8653,8662,8675,8725,8731,8734,8735,8746,8773,8774,8780,8782,8794,8807,8840,8870,8873,8874,8879,8880,8881,8884,8886,8888,8891,8894,8895,8896,8900,8901,8903,8904,8906,8908,8913,8914,8918,8923,8934,8935,8937,8938,8942,8957,8959,8960,8963,8964,8973,8974,8977,8979,8998,8999,9002,9007,9016,9019,9022,9027,9034,9037,9040,9042,9045,9047,9049,9053,9055,9060,9067,9070,9072,9073,9076,9078,9080,9082,9083,9086,9088,9090,9097,9102,9104",
	//		},
	//		{
	//			Username: "张秀梅",
	//			Count:    283,
	//			IDs:      "7793,7800,7810,7825,7842,7845,7854,7863,7864,7865,7866,7867,7871,7873,7891,7892,7893,7894,7896,7897,7899,7906,7907,7908,7909,7914,7917,7927,7938,7939,7940,7945,7946,7948,7956,7957,7958,7961,7965,7969,7973,7979,7981,7982,7983,7984,7985,7986,7990,7991,8077,8112,8132,8189,8217,8218,8228,8306,8316,8353,8354,8356,8357,8388,8393,8424,8432,8433,8477,8642,8647,8684,8685,8706,8792,8804,8821,8824,8875,8997,9004,9006,9010,9028,9032,9054,9077,9092,9111",
	//		},
	//		{
	//			Username: "周群英",
	//			Count:    276,
	//			IDs:      "8003,8006,8012,8014,8018,8019,8022,8034,8037,8038,8045,8048,8050,8052,8065,8075,8081,8083,8084,8088,8089,8098,8102,8108,8115,8136,8235,8288,8290,8292,8302,8322,8323,8331,8370,8381,8382,8390,8394,8405,8490,8501,8504,8575,8611,8619,8652,8664,8678,8758,8762,8777,8798,8806,8834,8868,8869,8871,8876,8882,8887,8893,8905,8907,8915,8916,8921,8924,8932,8954,8984,9026,9030,9036,9050,9089,9095,9116,9118,9121,9122,9123",
	//		},
	//		{
	//			Username: "任华威",
	//			Count:    269,
	//			IDs:      "7795,7796,7798,7799,7801,7804,7806,7807,7814,7816,7820,7822,7823,7828,7829,7830,7831,7832,7833,7834,7837,7838,7839,7840,7841,7843,7844,7862,7870,7876,7880,7920,7921,7923,7924,7937,7964,7971,7972,7980,8205,8212,8263,8268,8391,8403,8410,8454,8459,8460,8461,8469,8496,8502,8528,8529,8532,8533,8590,8632,8638,8673,8827,8892,8929,8939,8940,8941,8943,8944,8945,8947,8951,8952,8953,8966,9108,9109",
	//		},
	//		{
	//			Username: "王琳",
	//			Count:    265,
	//			IDs:      "7861,7868,7869,7874,7877,7884,7886,7887,7888,7889,7890,7895,7898,7902,7903,7904,7905,7910,7912,7913,7915,7919,7926,7930,7931,7932,7933,7944,7947,7950,7954,7959,7960,7967,7976,7987,7988,8004,8064,8117,8118,8170,8203,8264,8285,8371,8397,8809,8810,8812,8927,8990,8992,9011,9012,9091",
	//		},
	//		{
	//			Username: "刘春悦",
	//			Count:    253,
	//			IDs:      "7925,7935,8341,8367,8417,8434,8471,8480,8503,8505,8522,8523,8524,8530,8531,8537,8538,8539,8540,8546,8547,8548,8550,8551,8552,8554,8573,8574,8583,8586,8588,8592,8596,8597,8598,8600,8603,8610,8620,8621,8622,8624,8640,8644,8654,8660,8665,8668,8697,8698,8699,8700",
	//		},
	//		{
	//			Username: "高慧莲",
	//			Count:    251,
	//			IDs:      "8447,8452,8690,8695,8701,8705,8707,8779,8784,8785,8786,8802,8803,8814,8815,8818,8819,8820,8822,8823,8825,8828,8850,8853,8860,8862,8863,8909,8930,9000,9001,9005,9013,9018,9023,9052,9058,9061,9062,9063,9068,9074",
	//		},
	//		{
	//			Username: "金湘琴",
	//			Count:    247,
	//			IDs:      "7936,7952,7953,7955,8293,8335,8337,8338,8429,8484,8485,8495,8507,8508,8509,8578,8579,8585,8623,8626,8629,8636,8649,8650,8651,8655,8693,8694,8788,8845,8848,8852",
	//		},
	//		{
	//			Username: "刘敏",
	//			Count:    241,
	//			IDs:      "7827,7881,7882,7883,7885,7900,7901,7911,7916,7928,7951,7974,7975,7977,8124,8230,8232,8259,8278,8300,8332,8334,8358,8437,8525,8576,8661,8667,8710,8722,8728,8793",
	//		},
	//	},
	//	ServedRank: []dashboard.RankInfo{
	//		{
	//			Username: "吴秀丽",
	//			Count:    211,
	//			IDs:      "5,30,35,7766,7768,7769,7770,7771,7772,7773,7774,7775,7815,7858,7879,7922,7934,7941,7970,7989,8021,8041,8043,8055,8070,8093,8113,8126,8127,8128,8129,8130,8131,8133,8134,8135,8137,8138,8139,8140,8141,8142,8143,8144,8145,8146,8147,8148,8149,8150,8152,8155,8158,8160,8161,8164,8165,8166,8167,8171,8172,8173,8174,8175,8176,8177,8178,8179,8180,8181,8182,8183,8184,8185,8186,8187,8188,8191,8192,8193,8195,8197,8198,8199,8200,8201,8202,8206,8209,8210,8211,8213,8214,8215,8216,8219,8220,8221,8222,8223,8224,8225,8226,8227,8231,8233,8234,8236,8237,8238,8242,8243,8244,8245,8246,8247,8248,8249,8250,8252,8253,8254,8255,8256,8257,8261,8262,8265,8266,8267,8269,8270,8273,8274,8275,8276,8277,8279,8280,8281,8282,8283,8284,8286,8287,8289,8291,8294,8295,8299,8301,8303,8304,8307,8308,8309,8312,8313,8314,8315,8319,8320,8325,8333,8339,8340,8343,8344,8345,8349,8350,8351,8352,8359,8360,8361,8362,8363,8364,8365,8366,8368,8372,8373,8376,8377,8378,8380,8383,8384,8385,8386,8387,8389,8392,8399,8401,8402,8404,8406,8412,8413,8414,8415,8416,8418,8419,8420,8421,8423,8425,8428,8431,8436,8440,8441,8442,8446,8449,8463,8465,8466,8468,8475,8476,8481,8483,8489,8510,8527,8536,8542,8555,8589,8591,8595,8608,8612,8614,8643,8663,8687,8689,8692,8704,8712,8713,8719,8729,8737,8739,8742,8747,8756,8761,8770,8772,8791,8799,8805,8829,8830,8833,8835,8839,8843,8844,8846,8847,8849,8854,8855,8857,8864,8866,8867,8877,8878,8885,8889,8890,8897,8898,8899,8902,8910,8911,8917,8919,8920,8922,8925,8928,8931,8946,8948,8949,8950,8955,8956,8958,8962,8967,8968,8969,8970,8972,8975,8976,8978,8980,8981,8982,8983,8985,8986,8987,8988,8989,8991,8993,8994,8995,9003,9008,9009,9014,9015,9017,9024,9025,9029,9031,9033,9038,9039,9041,9043,9044,9046,9051,9056,9057,9059,9064,9071,9075,9079,9081,9084,9085,9087,9093,9094,9096,9098,9099,9100,9101,9103,9105,9106,9107,9110,9113,9114,9115,9117,9119,9120,9124,9125,9126,9127,9128",
	//		},
	//		{
	//			Username: "任新华",
	//			Count:    209,
	//			IDs:      "7780,7993,7994,7995,7996,7997,7998,7999,8000,8001,8002,8005,8007,8008,8009,8010,8011,8013,8015,8016,8017,8020,8023,8024,8025,8026,8027,8028,8029,8030,8031,8032,8033,8035,8036,8039,8040,8042,8044,8046,8047,8049,8051,8053,8057,8058,8059,8060,8061,8062,8063,8066,8067,8068,8069,8071,8072,8073,8074,8076,8078,8079,8080,8082,8085,8086,8087,8090,8091,8092,8094,8095,8097,8099,8100,8101,8103,8104,8105,8106,8107,8109,8110,8111,8114,8116,8119,8120,8121,8125,8153,8154,8156,8157,8162,8163,8168,8169,8194,8196,8204,8207,8239,8240,8241,8251,8258,8260,8271,8310,8311,8318,8324,8327,8328,8336,8375,8379,8398,8407,8411,8426,8443,8451,8456,8467,8470,8472,8486,8493,8498,8512,8535,8549,8601,8646,8653,8662,8675,8725,8731,8734,8735,8746,8773,8774,8780,8782,8794,8807,8840,8870,8873,8874,8879,8880,8881,8884,8886,8888,8891,8894,8895,8896,8900,8901,8903,8904,8906,8908,8913,8914,8918,8923,8934,8935,8937,8938,8942,8957,8959,8960,8963,8964,8973,8974,8977,8979,8998,8999,9002,9007,9016,9019,9022,9027,9034,9037,9040,9042,9045,9047,9049,9053,9055,9060,9067,9070,9072,9073,9076,9078,9080,9082,9083,9086,9088,9090,9097,9102,9104",
	//		},
	//		{
	//			Username: "杜小毛",
	//			Count:    199,
	//			IDs:      "7793,7800,7810,7825,7842,7845,7854,7863,7864,7865,7866,7867,7871,7873,7891,7892,7893,7894,7896,7897,7899,7906,7907,7908,7909,7914,7917,7927,7938,7939,7940,7945,7946,7948,7956,7957,7958,7961,7965,7969,7973,7979,7981,7982,7983,7984,7985,7986,7990,7991,8077,8112,8132,8189,8217,8218,8228,8306,8316,8353,8354,8356,8357,8388,8393,8424,8432,8433,8477,8642,8647,8684,8685,8706,8792,8804,8821,8824,8875,8997,9004,9006,9010,9028,9032,9054,9077,9092,9111",
	//		},
	//		{
	//			Username: "崔佳南",
	//			Count:    193,
	//			IDs:      "8003,8006,8012,8014,8018,8019,8022,8034,8037,8038,8045,8048,8050,8052,8065,8075,8081,8083,8084,8088,8089,8098,8102,8108,8115,8136,8235,8288,8290,8292,8302,8322,8323,8331,8370,8381,8382,8390,8394,8405,8490,8501,8504,8575,8611,8619,8652,8664,8678,8758,8762,8777,8798,8806,8834,8868,8869,8871,8876,8882,8887,8893,8905,8907,8915,8916,8921,8924,8932,8954,8984,9026,9030,9036,9050,9089,9095,9116,9118,9121,9122,9123",
	//		},
	//		{
	//			Username: "万永建",
	//			Count:    185,
	//			IDs:      "7795,7796,7798,7799,7801,7804,7806,7807,7814,7816,7820,7822,7823,7828,7829,7830,7831,7832,7833,7834,7837,7838,7839,7840,7841,7843,7844,7862,7870,7876,7880,7920,7921,7923,7924,7937,7964,7971,7972,7980,8205,8212,8263,8268,8391,8403,8410,8454,8459,8460,8461,8469,8496,8502,8528,8529,8532,8533,8590,8632,8638,8673,8827,8892,8929,8939,8940,8941,8943,8944,8945,8947,8951,8952,8953,8966,9108,9109",
	//		},
	//		{
	//			Username: "毛冠英",
	//			Count:    183,
	//			IDs:      "7861,7868,7869,7874,7877,7884,7886,7887,7888,7889,7890,7895,7898,7902,7903,7904,7905,7910,7912,7913,7915,7919,7926,7930,7931,7932,7933,7944,7947,7950,7954,7959,7960,7967,7976,7987,7988,8004,8064,8117,8118,8170,8203,8264,8285,8371,8397,8809,8810,8812,8927,8990,8992,9011,9012,9091",
	//		},
	//		{
	//			Username: "傅妙琴",
	//			Count:    181,
	//			IDs:      "7925,7935,8341,8367,8417,8434,8471,8480,8503,8505,8522,8523,8524,8530,8531,8537,8538,8539,8540,8546,8547,8548,8550,8551,8552,8554,8573,8574,8583,8586,8588,8592,8596,8597,8598,8600,8603,8610,8620,8621,8622,8624,8640,8644,8654,8660,8665,8668,8697,8698,8699,8700",
	//		},
	//		{
	//			Username: "蒋宝丽",
	//			Count:    178,
	//			IDs:      "8447,8452,8690,8695,8701,8705,8707,8779,8784,8785,8786,8802,8803,8814,8815,8818,8819,8820,8822,8823,8825,8828,8850,8853,8860,8862,8863,8909,8930,9000,9001,9005,9013,9018,9023,9052,9058,9061,9062,9063,9068,9074",
	//		},
	//		{
	//			Username: "卢含",
	//			Count:    174,
	//			IDs:      "7936,7952,7953,7955,8293,8335,8337,8338,8429,8484,8485,8495,8507,8508,8509,8578,8579,8585,8623,8626,8629,8636,8649,8650,8651,8655,8693,8694,8788,8845,8848,8852",
	//		},
	//		{
	//			Username: "陈淑燕",
	//			Count:    172,
	//			IDs:      "7827,7881,7882,7883,7885,7900,7901,7911,7916,7928,7951,7974,7975,7977,8124,8230,8232,8259,8278,8300,8332,8334,8358,8437,8525,8576,8661,8667,8710,8722,8728,8793",
	//		},
	//	},
	//	ExcellentRank: []dashboard.RankInfo{
	//		{
	//			Username: "苏晨",
	//			Count:    101,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "李天舒",
	//			Count:    94,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "刘素娟",
	//			Count:    91,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "朱艳",
	//			Count:    87,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "刘涛",
	//			Count:    82,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "刘婷婷",
	//			Count:    81,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "黄向红",
	//			Count:    77,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "王波",
	//			Count:    74,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "王丽秋",
	//			Count:    72,
	//			IDs:      "",
	//		},
	//		{
	//			Username: "傅伟",
	//			Count:    70,
	//			IDs:      "",
	//		},
	//	},
	//}
	return
}

// GetScStewardData 获取全部服务中心数据大屏【服务中心】
func (s *BordService) GetScStewardData(centreID uint) (stewardDashboard dashboard.Steward, err error) {
	var register int64
	var stations []system.SysUser
	if stationsErr := global.GVA_DB.Model(&system.SysUser{}).Where("authority_id = 444 AND creator = ?", centreID).Find(&stations).Error; stationsErr != nil {
		return
	}
	var ids []uint
	for _, v := range stations {
		ids = append(ids, v.ID)
	}
	err = global.GVA_DB.Model(&manager.FdHealthManager{}).Where("is_register = ? AND store_id IN (?)", true, ids).Count(&register).Error
	if err != nil {
		return
	}
	stewardDashboard.Application = register
	var audit int64
	err = global.GVA_DB.Model(&manager.FdHealthManager{}).Where("is_audit = ? AND store_id IN (?)", true, ids).Count(&audit).Error
	if err != nil {
		return
	}
	stewardDashboard.Incumbency = audit
	// 计算健管师界别分组
	var managers []manager.FdHealthManager
	err = global.GVA_DB.Find(&managers).Error
	if err != nil {
		return
	}
	var primary int64
	var intermediate int64
	var senior int64
	for i := range managers {
		if managers[i].Level == 0 {
			primary++
		}
		if managers[i].Level == 1 {
			intermediate++
		}
		if managers[i].Level == 2 {
			senior++
		}
	}
	stewardDashboard.LevelProportion = []dashboard.Pie{
		{
			Name:  "初级",
			Value: primary,
		},
		{
			Name:  "中级",
			Value: intermediate,
		},
		{
			Name:  "高级",
			Value: senior,
		},
	}
	//用 direct_num + indirect_num 倒叙排列取前10
	var top10 []manager.FdHealthManager
	err = global.GVA_DB.Order("direct_num + indirect_num desc").Limit(10).Find(&top10, "store_id IN (?)", ids).Error
	if err != nil {
		return
	}
	var RegistrantsUser dashboard.RankInfo
	// 注册人数排行
	for i := range top10 {
		global.GVA_DB.Model(&user.User{}).Select("GROUP_CONCAT(id) AS IDs").Where("steward_id = ?", top10[i].HmId).Scan(&RegistrantsUser)
		stewardDashboard.RegistrantsRank = append(stewardDashboard.RegistrantsRank, dashboard.RankInfo{
			Username: top10[i].Name,
			Count:    *top10[i].DirectNum + *top10[i].IndirectNum,
			IDs:      RegistrantsUser.IDs,
		})
	}
	//用 score 倒叙排列取前10
	var top10Score []manager.FdHealthManager
	err = global.GVA_DB.Order("score desc").Limit(10).Find(&top10Score, "store_id IN (?)", ids).Error
	if err != nil {
		return
	}
	for i := range top10Score {
		score := 0
		if top10Score[i].Score != 0 {
			score = int(top10Score[i].Score)
		}
		stewardDashboard.ExcellentRank = append(stewardDashboard.ExcellentRank, dashboard.RankInfo{
			Username: top10Score[i].Name,
			Count:    score,
		})
	}
	// 统计服务人数 倒叙排列取前10
	var ServiceUser []dashboard.RankInfo
	yesterday := time.Now().AddDate(0, 0, -1)
	startTime := yesterday.Format("2006-01-02")
	endTime := time.Now().Format("2006-01-02")
	var healthManagers []manager.FdHealthManager
	if healthManagersErr := global.GVA_DB.Model(&manager.FdHealthManager{}).Find(&healthManagers, "store_id IN (?)", ids).Error; healthManagersErr != nil {
		return
	}
	var HmIDs []uint
	for _, v := range healthManagers {
		HmIDs = append(HmIDs, v.HmId)
	}
	err = global.GVA_DB.Model(&manager.MessageRemind{}).
		Select("fd_health_manager.name AS username, COUNT( DISTINCT user_id ) AS count, GROUP_CONCAT(user_id) AS IDs").
		Joins("LEFT JOIN fd_health_manager on fd_message_remind.hm_id = fd_health_manager.hm_id").
		Where("fd_message_remind.created_at BETWEEN ? AND ? AND fd_message_remind.hm_id IN (?)", startTime, endTime, HmIDs).
		Group("fd_health_manager.hm_id").Order("count DESC").Limit(10).Scan(&ServiceUser).Error
	stewardDashboard.ServedRank = ServiceUser
	return
}

// GetDailyNewUsers 获取每日新增用户
func (s *BordService) GetDailyNewUsers(HmId uint) (stewardDashboard dashboard.DailyNewUsers, err error) {
	// 获取今天之前每天的日期
	var dates []string
	now := time.Now()
	for i := 7; i >= 1; i-- {
		date := now.AddDate(0, 0, -i).Format("01.02")
		dates = append(dates, date)
	}

	// 查询并统计数据
	var result []struct {
		Date string `json:"date"`
		Num  uint   `json:"num"`
	}
	err = global.GVA_DB.Model(&user.User{}).
		Select("DATE_FORMAT(created_at, '%m.%d') as date, COUNT(*) as num").
		Where("steward_id = ? AND created_at >= ?", HmId, time.Now().AddDate(0, 0, -8)).
		Group("date").
		Order("date").
		Find(&result).Error

	// 构建结果，确保每天都在结果中
	stewardDashboard = dashboard.DailyNewUsers{Date: dates, Num: make([]uint, len(dates))}
	for i, date := range dates {
		for _, r := range result {
			if r.Date == date {
				stewardDashboard.Num[i] = r.Num
				break
			}
		}
	}
	return
}

// GetDayNewUserList 获取当日新增用户列表
func (s *BordService) GetDayNewUserList(info userReq.UserSearch) (list []userRes.DayNewUserList, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&user.User{}).Where("steward_id = ?", info.StewardID)
	// 如果有条件搜索 下方会自动创建搜索语句
	if !info.StartCreatedAt.Equal(time.Time{}) {
		// 计算次日时间
		location := time.FixedZone("CST", 8*60*60) // CST is China Standard Time
		currentDayStart := time.Date(info.StartCreatedAt.Year(), info.StartCreatedAt.Month(), info.StartCreatedAt.Day(), 0, 0, 0, 0, location)
		currentDayEnd := time.Date(info.StartCreatedAt.Year(), info.StartCreatedAt.Month(), info.StartCreatedAt.Day(), 23, 59, 59, 0, location)
		db = db.Where("created_at BETWEEN ? AND ?", currentDayStart, currentDayEnd)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Find(&list).Error
	return
}

// GetUserData 获取会员数据
func (s *BordService) GetUserData(HmId uint) (list []userRes.UserData, err error) {
	result := []userRes.UserData{
		{
			Value: 0,
			Name:  "注册用户",
		},
		{
			Value: 0,
			Name:  "会员总数",
		},
		{
			Value: 0,
			Name:  "过期会员",
		},
	}
	err = global.GVA_DB.Model(&user.User{}).Select("types as name, COUNT(*) as value").Where("steward_id = ?", HmId).Group("types").Scan(&list).Error
	// 填充预定义的结构体列表
	for i := range result {
		for _, r := range list {
			if result[i].Name == userTypeToString(r.Name) {
				result[i].Value = r.Value
				break
			}
		}
	}
	return result, err
}

// GetSexAndAgeRatio 获取性别年龄占比
func (s *BordService) GetSexAndAgeRatio(HmId uint) (ratio dashboard.SexAndAgeRatio, err error) {
	var users []user.User
	err = global.GVA_DB.Where("steward_id = ? AND birthday is not null", HmId).Find(&users).Error
	var man int64
	var woman int64
	ageGroup := make(map[string]int64)
	for i := range users {
		if users[i].Sex == 1 {
			man++
		}
		if users[i].Sex == 2 {
			woman++
		}
		//当前时间 - users[i].Birthday 计算年龄
		age := time.Now().Year() - users[i].Birthday.Year()
		if age < 25 {
			ageGroup["25以下"]++
		} else if age >= 25 && age <= 35 {
			ageGroup["26-35"]++
		} else if age >= 36 && age <= 45 {
			ageGroup["36-45"]++
		} else if age >= 46 && age <= 55 {
			ageGroup["46-55"]++
		} else if age >= 56 && age <= 65 {
			ageGroup["56-65"]++
		} else if age >= 66 && age <= 75 {
			ageGroup["66-75"]++
		} else if age >= 76 && age <= 85 {
			ageGroup["76-85"]++
		} else if age > 85 {
			ageGroup["85以上"]++
		}
	}
	ratio.SexPie = []dashboard.Ratio{
		{
			Name:  "男",
			Value: man,
		},
		{
			Name:  "女",
			Value: woman,
		},
	}
	ratio.AgePie = []dashboard.Ratio{
		{
			Name:  "25以下",
			Value: ageGroup["25以下"],
		},
		{
			Name:  "26-35",
			Value: ageGroup["26-35"],
		},
		{
			Name:  "36-45",
			Value: ageGroup["36-45"],
		},
		{
			Name:  "46-55",
			Value: ageGroup["46-55"],
		},
		{
			Name:  "56-65",
			Value: ageGroup["56-65"],
		},
		{
			Name:  "66-75",
			Value: ageGroup["66-75"],
		},
		{
			Name:  "76-85",
			Value: ageGroup["76-85"],
		},
		{
			Name:  "85以上",
			Value: ageGroup["85以上"],
		},
	}
	return
}

// GetDiseaseTop 获取病症TOP
func (s *BordService) GetDiseaseTop(HmId uint) (list []dashboard.DiseaseTOP, err error) {
	// 获取该健管师下用户id集合
	var users []user.User
	err = global.GVA_DB.Model(&user.User{}).Where("steward_id = ?", HmId).Find(&users).Error
	var userIDs []uint
	for _, v := range users {
		userIDs = append(userIDs, v.ID)
	}
	// 查询病症报告记录
	var records []disease.DiseaseReportRecord
	err = global.GVA_DB.Where("uid IN (?)", userIDs).Find(&records).Error
	// 统计病症出现次数
	//symptomCount := make(map[string]int)
	symptomCount := make(map[string]struct {
		Name  string `json:"Name"`
		Count int    `json:"Count"`
	})
	visitedSymptoms := make(map[uint]map[string]bool)
	for _, record := range records {
		userID := record.Uid
		if visitedSymptoms[userID] == nil {
			visitedSymptoms[userID] = make(map[string]bool)
		}
		// 处理没有逗号拼接的情况
		symptomIDs := strings.Split(record.BzIDs, ",")
		if len(symptomIDs) == 1 && symptomIDs[0] == "" {
			symptomIDs = []string{}
		}
		for _, symptomID := range symptomIDs {
			if _, ok := visitedSymptoms[userID][symptomID]; !ok {
				var symptom health.Disease
				global.GVA_DB.Where("id = ?", symptomID).First(&symptom)

				symptomCount[symptomID] = struct {
					Name  string `json:"Name"`
					Count int    `json:"Count"`
				}{Name: symptom.Name, Count: symptomCount[symptomID].Count + 1}
				visitedSymptoms[userID][symptomID] = true
			}
		}
	}
	for id, info := range symptomCount {
		list = append(list, struct {
			BzID  string `json:"bz_id"`
			Name  string `json:"name"`
			Count int    `json:"count"`
		}{BzID: id, Name: info.Name, Count: info.Count})
	}
	// 按出现次数降序排序
	sort.Slice(list, func(i, j int) bool {
		return list[i].Count > list[j].Count
	})
	// 只保留前十个病症
	if len(list) > 10 {
		list = list[:10]
	}
	return
}

// GetDiseaseUserList 获取病症用户列表
func (s *BordService) GetDiseaseUserList(HmId uint, id string) (list []dashboard.DiseaseUserList, err error) {
	var users []user.User
	err = global.GVA_DB.Where("steward_id = ?", HmId).Select("id").Order("id ASC").Find(&users).Error
	if len(users) == 0 {
		return nil, errors.New("你还没有邀请的用户")
	}
	var userIDs []uint
	for _, v := range users {
		userIDs = append(userIDs, v.ID)
	}
	err = global.GVA_DB.Model(&disease.DiseaseReportRecord{}).
		Where("FIND_IN_SET(?, bz_ids) > 0 AND uid IN (?)", id, userIDs).
		Pluck("DISTINCT uid", &userIDs).Error
	for _, val := range userIDs {
		var userinfo user.User
		err = global.GVA_DB.Where("id = ?", val).First(&userinfo).Error
		list = append(list, dashboard.DiseaseUserList{
			UID:   userinfo.ID,
			Name:  userinfo.Name,
			Phone: userinfo.Phone,
		})
	}
	return
}

// GetDayServiceNum 获取今日服务人数
func (s *BordService) GetDayServiceNum(HmId uint) (list map[string]interface{}, err error) {
	// 统计在管人数
	var memberCount int64
	err = global.GVA_DB.Model(&user.User{}).Where("steward_id = ? AND types = 2", HmId).Count(&memberCount).Error
	yesterday := time.Now().AddDate(0, 0, -1)
	startTime := yesterday.Format("2006-01-02")
	endTime := time.Now().Format("2006-01-02")
	// 统计服务人数
	var serviceCount int64
	err = global.GVA_DB.Model(&manager.MessageRemind{}).Where("hm_id = ? AND created_at BETWEEN ? AND ?", HmId, startTime, endTime).Count(&serviceCount).Error
	// 统计未服务人数
	//var noServiceCount int64
	//err = global.GVA_DB.Debug().Model(&user.User{}).
	//	Where("steward_id = ? AND types = ?", HmId, 2).
	//	Not("ID IN (SELECT user_id FROM fd_message_remind WHERE hm_id = ? AND created_at BETWEEN ? AND ?)", HmId, startTime, endTime).
	//	Count(&noServiceCount).Error
	list = map[string]interface{}{
		"manage_num":       memberCount,
		"service_num":      serviceCount,
		"no_service_count": memberCount - serviceCount, // 直接减法更快
	}
	return
}

// GetPlanCompleteInfo 获取方案完成信息
func (s *BordService) GetPlanCompleteInfo(HmId uint) (info dashboard.PlanCompleteInfo, err error) {
	// 获取当前健管师的推广用户
	var users []user.User
	err = global.GVA_DB.Where("steward_id = ?", HmId).Select("id,name,phone").Order("id ASC").Find(&users).Error
	if len(users) == 0 {
		return info, errors.New("你还没有推广用户")
	}
	// 获取今天起止时间范围
	//today := time.Now().Format("2006-01-02")
	//tomorrow := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
	yesterday := time.Now().AddDate(0, 0, -1)
	startTime := yesterday.Format("2006-01-02")
	endTime := time.Now().Format("2006-01-02")
	var completedCount int
	var completeInfo []dashboard.CompleteInfo
	for _, v := range users {
		var plan catering.Food
		result := global.GVA_DB.Select("id,breakfast,lunch,dinner,brain,sport").First(&plan, "user_id = ? AND created_at BETWEEN ? AND ?", v.ID, startTime, endTime).Error
		if errors.Is(result, gorm.ErrRecordNotFound) || result != nil {
			continue
		}
		schedule := calculateSchedule(&plan)
		if schedule == "100%" {
			completedCount++
		}
		completeInfo = append(completeInfo, dashboard.CompleteInfo{
			ID:       v.ID,
			Name:     v.Name,
			Phone:    v.Phone,
			Schedule: schedule,
		})
	}
	info = dashboard.PlanCompleteInfo{
		FinishNum:    completedCount,
		NoFinishNum:  len(users) - completedCount,
		CompleteInfo: completeInfo,
	}
	return
}

// GetHealthRecords 获取健康档案信息
func (s *BordService) GetHealthRecords(userID string) (info dashboard.HealthRecords, err error) {
	//var userInfo user.User
	//err = global.GVA_DB.Where("id = ?", userID).First(&userInfo).Error
	var physique assess.PhysiqueQuestionLog
	physiqueInfo := global.GVA_DB.Preload("User").Order("id DESC").Limit(1).Find(&physique, "uid = ?", userID)
	if errors.Is(physiqueInfo.Error, gorm.ErrRecordNotFound) {
		return info, errors.New("该用户暂无体质检测记录")
	}
	var record disease.DiseaseReportRecord
	recordInfo := global.GVA_DB.Order("created_at DESC").Preload("User").Preload("Physique").First(&record, "uid = ?", userID)
	if errors.Is(recordInfo.Error, gorm.ErrRecordNotFound) {
		return info, errors.New("该用户暂无病症报告记录")
	}
	// 拼接返回数据
	info.Name = record.User.Name
	info.Sex = getSexString(record.User.Sex)
	info.Birthday = record.User.Birthday
	info.Physique = record.Physique.Name
	info.BloodType = physique.BloodType
	info.BloodSugar = physique.BloodSugar
	info.BloodOxygen = physique.BloodConcentration
	info.HeartRate = physique.HRres
	info.LowPressure = physique.LowTension
	info.HighPressure = physique.HighTension
	// 处理返回病症数据
	var diseases []health.Disease
	err = global.GVA_DB.Where("id IN (?)", strings.Split(record.BzIDs, ",")).Find(&diseases).Error
	for _, value := range diseases {
		info.Diseases = append(info.Diseases, dashboard.Disease{Disease: value.Name})
	}
	// 处理返回体态评估信息
	var tt body.HealthManageTag
	err = global.GVA_DB.Order("created_at DESC").First(&tt, "uid = ? AND types = 2", userID).Error
	// 解析部位ID和部位疼痛ID
	placeTypesIDs := strings.Split(tt.PlaceTypes, ",")
	for _, placeTypeID := range placeTypesIDs {
		var healthManage body.HealthManage
		err = global.GVA_DB.Where("ID = ?", placeTypeID).Preload("HealthManageChilds").First(&healthManage).Error
		posture := dashboard.Posture{
			Position: healthManage.Name,
			Symptom:  make([]dashboard.PostureSymptom, 0),
		}
		placeIDs := strings.Split(tt.Place, ",")
		for _, placeID := range placeIDs {
			for _, child := range healthManage.HealthManageChilds {
				if strconv.Itoa(int(child.ID)) == placeID {
					symptom := dashboard.PostureSymptom{
						Id:   child.ID,
						Name: child.Name,
					}
					posture.Symptom = append(posture.Symptom, symptom)
				}
			}
		}
		info.Posture = append(info.Posture, posture)
	}
	// 处理返回病史信息
	var history disease.UserDiseaseHistory
	historyInfo := global.GVA_DB.First(&history, "id = ?", userID)
	if errors.Is(historyInfo.Error, gorm.ErrRecordNotFound) {
		return info, errors.New("该用户暂无病史记录")
	}
	info.NowMedicalHistory.NowSymptom = history.Current
	info.NowMedicalHistory.NowMeasure = history.CMeasure
	info.NowMedicalHistory.NowSituation = history.CDrugInfo
	info.PastMedicalHistory.PastSymptom = history.Past
	info.PastMedicalHistory.PastMeasure = history.PMeasure
	info.PastMedicalHistory.PastSituation = history.PDrugInfo
	return
}

// GetPromotionList 获取推广名单信息
func (s *BordService) GetPromotionList(userID string) (info dashboard.PromotionRoster, err error) {
	// 查询指定用户信息
	var userInfo user.User
	err = global.GVA_DB.Where("id = ?", userID).First(&userInfo).Error
	var users []user.User
	err = global.GVA_DB.Where("invite_user_id = ?", userID).Find(&users).Error
	info.Name = userInfo.Name
	info.PromotionNum = len(users)
	info.Score = userInfo.Points
	info.Province = userInfo.Province
	info.City = userInfo.City
	info.Area = userInfo.Area
	info.Addr = userInfo.Addr
	info.Promotions = users
	return
}

// 用户类型转换字符串
func userTypeToString(userType string) string {
	switch userType {
	case "1":
		return "注册用户"
	case "2":
		return "会员总数"
	case "3":
		return "过期会员"
	default:
		return "注册用户"
	}
}

// 计算完成进度百分比
func calculateSchedule(food *catering.Food) string {
	completedCount := 0
	if food.Breakfast != nil {
		completedCount++
	}
	if food.Lunch != nil {
		completedCount++
	}
	if food.Dinner != nil {
		completedCount++
	}
	if food.Brain != nil {
		completedCount++
	}
	if food.Sport != nil {
		completedCount++
	}
	percentage := float64(completedCount) / 5 * 100
	return fmt.Sprintf("%.0f%%", percentage)
}

// getSexString 获取性别字符串
func getSexString(sex uint) string {
	if sex == 1 {
		return "男"
	} else {
		return "女"
	}
}
